dpm91915 2019-05-24 00:11
浏览 311

如何正确停止ajax请求

I'm trying to stop an Ajax request when a user click a button. But even if I made use the .abort(); the ajax keep requesting each 2 seconds. Basically, a user wait for an input from the server. If the response is 2, then after 2 second an ajax request need to be call. If the response is 3, then is it good. the function is not called anymore.

I tried different solutions, .arbord(); changed the ajax completely...etc None of the solution worked out. I guess I'm missing some concept here.

////////////////////// 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条回答 默认 最新

  • dousuowu4610 2019-05-24 09:01
    关注

    Declare the variable jqXHR outside of the CheckStatus() function

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

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题