【问题标题】:How to stop a ajax request properly如何正确停止ajax请求
【发布时间】:2019-05-24 20:25:42
【问题描述】:

我试图在用户单击按钮时停止 Ajax 请求。但即使我使用了 .abort(); ajax 每 2 秒请求一次。基本上,用户等待来自服务器的输入。如果响应为 2,则 2 秒后需要调用 ajax 请求。如果响应是 3,那么它是好的。该函数不再被调用。

我尝试了不同的解决方案,.arbord();完全改变了ajax ...等没有一个解决方案成功。我想我在这里遗漏了一些概念。

////////////////////// index.php 
.
<button id="cancel" onclick="CancelRequest()">Cancel</button>
.
<script>
function CheckStatus(){

var jqXHR = $.ajax({ 
   url: "status.php",
   async: true,
   cache: false,
   type: "POST",
   data: {data: id},
   success: function(response){
      var response;
if (response == 2) {
    alert(response);
    setTimeout(CheckStatus, 2000);   /// NEED TO SEND THE REQUEST AJAX REQUEST AGAIN, the response needs to be 3
} else if (response == 3) { 
    alert("good");
} else {
    alert("error");
}     
}
}); 

}

CheckStatus(); // start ajax automatically
}


//cancel request if the user press a button

function CancelRequest() {
    jqXHR.abort();

}
</script>


///////////////////////////////////// status.php 

$number = $_POST['id'];
.
.
.
.
$number = 2;

if ($number['status'] === 3) {
    echo "good";
} elseif ($result['status'] == 2) {
    echo "repeat again";
} else {
    echo "error";
}

I expect that when I call jqXHR.abort(); the ajax should stop. However it keep going forever.

【问题讨论】:

  • 如果你忘记了 IE 而忘记了 jQuery 那么:developer.mozilla.org/en-US/docs/Web/API/…
  • 我想你可以试试clearTimeout() in CancelRequest
  • 感谢您的回复,但我想我没有明白。基本上,用户在 index.php 中登录。 js 脚本发送请求以检查服务器是否得到答案,但是用户可以通过单击按钮来决定停止。我不明白为什么ajax 继续运行。再次感谢
  • 我认为问题不是 ajax。当您取消 ajax 时,有时在事件循环中有一个事件 CheckStatus 等待 2s 运行,它使 ajax 继续运行。使用 clearTimeout 清除此事件。试试my example,当你不使用clearTimeout时,ajax继续运行
  • 这里已经给出了答案...stackoverflow.com/questions/4551175/…

标签: javascript php jquery ajax


【解决方案1】:

CheckStatus()函数之外声明变量jqXHR

<script>
var jqXHR; 
function CheckStatus(){
   jqXHR = $.ajax({ 
      url: "status.php",
      async: true,
      cache: false,
      type: "POST",
      data: {data: id},
      success: function(response){
               var response;
               if (response == 2) {
                 alert(response);
                 setTimeout(CheckStatus, 2000);   /// NEED TO SEND THE REQUEST AJAX REQUEST AGAIN, the response needs to be 3
               } else if (response == 3) { 
                  alert("good");
               } else {
                 alert("error");
               }     
          }
   }); 
}

 CheckStatus(); // start ajax automatically
}


//cancel request if the user press a button
function CancelRequest() {
    jqXHR.abort();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    相关资源
    最近更新 更多