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


当前回答

我已经分享了一个演示,演示了如何取消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);   
});

其他回答

AJAX请求可能无法按启动顺序完成。您可以选择忽略除最新的AJAX响应之外的所有AJAX响应,而不是放弃:

创建计数器启动AJAX请求时增加计数器使用计数器的当前值“标记”请求在成功回调中,将标记与计数器进行比较,以检查它是否是最近的请求

代码大纲:

var xhrCount = 0;
function sendXHR() {
    // sequence number for the current invocation of function
    var seqNumber = ++xhrCount;
    $.post("/echo/json/", { delay: Math.floor(Math.random() * 5) }, function() {
        // this works because of the way closures work
        if (seqNumber === xhrCount) {
            console.log("Process the response");
        } else {
            console.log("Ignore the response");
        }
    });
}
sendXHR();
sendXHR();
sendXHR();
// AJAX requests complete in any order but only the last 
// one will trigger "Process the response" message

jsFiddle演示

正如线程中的许多人所指出的,仅仅因为请求在客户端被中止,服务器仍然会处理该请求。这会在服务器上产生不必要的负载,因为它正在做我们已经停止在前端侦听的工作。

我试图解决的问题(其他人可能也会遇到)是,当用户在输入字段中输入信息时,我想发出一个请求,请求使用Google Instant类型的感觉。

为了避免发出不必要的请求并保持前端的快速性,我执行了以下操作:

var xhrQueue = [];
var xhrCount = 0;

$('#search_q').keyup(function(){

    xhrQueue.push(xhrCount);

    setTimeout(function(){

        xhrCount = ++xhrCount;

        if (xhrCount === xhrQueue.length) {
            // Fire Your XHR //
        }

    }, 150);

});

这将基本上每150毫秒发送一个请求(您可以根据自己的需要定制一个变量)。如果您无法理解这里到底发生了什么,请在If块之前将xhrCount和xhrQueue记录到控制台。

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

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

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

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

我已经分享了一个演示,演示了如何取消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);   
});