是否可以使用jQuery取消/中止尚未收到响应的Ajax请求?


当前回答

将所做的调用保存在数组中,然后对每个调用调用xhr.art()。

巨大的漏洞:你可以中止请求,但这只是客户端。服务器端可能仍在处理请求。如果您对会话数据使用PHP或ASP之类的东西,那么会话数据将被锁定,直到ajax完成。因此,为了允许用户继续浏览网站,必须调用session_write_close()。这将保存会话并将其解锁,以便等待继续的其他页面将继续。如果没有这一点,可能会有多个页面等待解除锁定。

其他回答

我正在进行实时搜索解决方案,需要取消可能比最新/最新请求花费更长时间的未决请求。

在我的案例中,我使用了这样的方法:

//On document ready
var ajax_inprocess = false;

$(document).ajaxStart(function() {
ajax_inprocess = true;
});

$(document).ajaxStop(function() {
ajax_inprocess = false;
});

//Snippet from live search function
if (ajax_inprocess == true)
{
    request.abort();
}
//Call for new request 

我们只需要解决这个问题,并测试了三种不同的方法。

按照@meouw的建议取消请求执行所有请求,但只处理最后一次提交的结果在另一个请求仍处于挂起状态时阻止新请求

变量Ajax1={调用:函数(){if(typeof this.xhr!==“undefined”)this.xhr.abourt();this.xhr=$.ajax({url:'您的/long/running/request/path',类型:'GET',成功:函数(数据){//过程响应}});}};变量Ajax2={计数器:0,调用:函数(){var self=此,seq=++此计数器;$.ajax美元({url:'您的/long/running/request/path',类型:'GET',成功:函数(数据){如果(seq==self.counter){//过程响应}}});}};变量Ajax3={活动:假,调用:函数(){如果(this.active==false){this.active=真;var self=this;$.ajax美元({url:'您的/long/running/request/path',类型:'GET',成功:函数(数据){//过程响应},完成:函数(){self.active=假;}});}}};$(函数){$(“#按钮”).click(函数(e){Ajax3.call();});})<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><input id=“button”type=“button“value=“click”/>

在我们的案例中,我们决定使用方法#3,因为它会减少服务器的负载。但我不能100%确定jQuery是否保证调用.complete()方法,这可能会导致死锁。在我们的测试中,我们无法再现这种情况。

我已经分享了一个演示,演示了如何取消AJAX请求——如果在预定义的等待时间内没有从服务器返回数据。

HTML格式:

<div id="info"></div>

JS代码:

var isDataReceived= false, waitTime= 1000; 
$(function() {
    // Ajax request sent.
     var xhr= $.ajax({
      url: 'http://api.joind.in/v2.1/talks/10889',
      data: {
         format: 'json'
      },     
      dataType: 'jsonp',
      success: function(data) {      
        isDataReceived= true;
        $('#info').text(data.talks[0].talk_title);        
      },
      type: 'GET'
   });
   // Cancel ajax request if data is not loaded within 1sec.
   setTimeout(function(){
     if(!isDataReceived)
     xhr.abort();     
   },waitTime);   
});

这是我基于以上许多答案的实现:

  var activeRequest = false; //global var
  var filters = {...};
  apply_filters(filters);

  //function triggering the ajax request
  function apply_filters(filters){
        //prepare data and other functionalities
        var data = {};
        //limit the ajax calls
        if (activeRequest === false){
          activeRequest = true;
        }else{
          //abort if another ajax call is pending
          $request.abort();
          //just to be sure the ajax didn't complete before and activeRequest it's already false
          activeRequest = true;        
        }

        $request = $.ajax({ 
          url : window.location.origin + '/your-url.php',
          data: data,
          type:'POST',
          beforeSend: function(){
            $('#ajax-loader-custom').show();
            $('#blur-on-loading').addClass('blur');
          },            
          success:function(data_filters){

              data_filters = $.parseJSON(data_filters);
              
              if( data_filters.posts ) {
                  $(document).find('#multiple-products ul.products li:last-child').after(data_filters.posts).fadeIn();
              }
              else{ 
                return;
              }
              $('#ajax-loader-custom').fadeOut();
          },
          complete: function() {
            activeRequest = false;
          }          
        }); 
  } 

以下代码显示了启动和中止Ajax请求:

function libAjax(){
  var req;
  function start(){

  req =    $.ajax({
              url: '1.php',
              success: function(data){
                console.log(data)
              }
            });

  }

  function stop(){
    req.abort();
  }

  return {start:start,stop:stop}
}

var obj = libAjax();

 $(".go").click(function(){


  obj.start();


 })



 $(".stop").click(function(){

  obj.stop();


 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="go" value="GO!" >
   <input type="button" class="stop" value="STOP!" >