如何正确停止Ajax请求

时间:2019-05-24 00:11:35

标签: javascript php jquery ajax

当用户单击按钮时,我试图停止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.

1 个答案:

答案 0 :(得分:1)

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

<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();
}