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


当前回答

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

  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!" >

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

按照@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.abourt(),就可以在发送类似这样的另一个请求之前中止任何挂起的ajax请求

//check for existing ajax request
if(ajax){ 
 ajax.abort();
 }
//then you make another ajax request
$.ajax(
 //your code here
  );

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

我试图解决的问题(其他人可能也会遇到)是,当用户在输入字段中输入信息时,我想发出一个请求,请求使用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;
          }          
        }); 
  }