我有一个问题,当提交表单时,所有活跃的ajax请求失败,并触发错误事件。

如何在jQuery中停止所有活动ajax请求而不触发错误事件?


每次你创建一个ajax请求,你可以使用一个变量来存储它:

var request = $.ajax({
    type: 'POST',
    url: 'someurl',
    success: function(result){}
});

然后你可以中止请求:

request.abort();

您可以使用一个数组来跟踪所有挂起的ajax请求,并在必要时中止它们。


以下是我目前正在使用的方法。

$.xhrPool = [];
$.xhrPool.abortAll = function() {
  _.each(this, function(jqXHR) {
    jqXHR.abort();
  });
};
$.ajaxSetup({
  beforeSend: function(jqXHR) {
    $.xhrPool.push(jqXHR);
  }
});

注意:_。js中的每一个都存在,但显然不是必需的。我只是懒惰,我不想把它改为$.each()。8页


安迪的代码有一些问题,但它给了我一些很好的想法。第一个问题是,我们应该弹出任何成功完成的jqXHR对象。我还必须修改abortAll函数。下面是我最终的工作代码:

$.xhrPool = [];
$.xhrPool.abortAll = function() {
            $(this).each(function(idx, jqXHR) {
                        jqXHR.abort();
                        });
};
$.ajaxSetup({
    beforeSend: function(jqXHR) {
            $.xhrPool.push(jqXHR);
            }
});
$(document).ajaxComplete(function() {
            $.xhrPool.pop();
            });

我不喜欢ajaxComplete()做事情的方式。无论我如何尝试配置. ajaxsetup,它都不工作。


下面的代码片段允许您维护一个请求列表(池),并在需要时中止它们。最好放在html的<HEAD>中,在任何其他AJAX调用之前。

<script type="text/javascript">
    $(function() {
        $.xhrPool = [];
        $.xhrPool.abortAll = function() {
            $(this).each(function(i, jqXHR) {   //  cycle through list of recorded connection
                jqXHR.abort();  //  aborts connection
                $.xhrPool.splice(i, 1); //  removes from list by index
            });
        }
        $.ajaxSetup({
            beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); }, //  annd connection to list
            complete: function(jqXHR) {
                var i = $.xhrPool.indexOf(jqXHR);   //  get index for current connection completed
                if (i > -1) $.xhrPool.splice(i, 1); //  removes from list by index
            }
        });
    })
</script>

使用ajaxSetup是不正确的,正如它的文档页面所指出的那样。它只设置默认值,如果某些请求覆盖了默认值,就会出现混乱。

我来晚了,但只是为了供将来参考,如果有人正在寻找解决同样问题的解决方案,这里是我的尝试,受到之前答案的启发,在很大程度上与之前的答案相同,但更完整

// Automatically cancel unfinished ajax requests 
// when the user navigates elsewhere.
(function($) {
  var xhrPool = [];
  $(document).ajaxSend(function(e, jqXHR, options){
    xhrPool.push(jqXHR);
  });
  $(document).ajaxComplete(function(e, jqXHR, options) {
    xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
  });
  var abort = function() {
    $.each(xhrPool, function(idx, jqXHR) {
      jqXHR.abort();
    });
  };

  var oldbeforeunload = window.onbeforeunload;
  window.onbeforeunload = function() {
    var r = oldbeforeunload ? oldbeforeunload() : undefined;
    if (r == undefined) {
      // only cancel requests if there is no prompt to stay on the page
      // if there is a prompt, it will likely give the requests enough time to finish
      abort();
    }
    return r;
  }
})(jQuery);

给每个xhr请求一个唯一的id,并在发送之前将对象引用存储在一个对象中。 在xhr请求完成后删除引用。

随时取消所有请求:

$.ajaxQ.abortAll();

返回被取消的请求的唯一id。仅用于测试目的。

工作职能:

$.ajaxQ = (function(){
  var id = 0, Q = {};

  $(document).ajaxSend(function(e, jqx){
    jqx._id = ++id;
    Q[jqx._id] = jqx;
  });
  $(document).ajaxComplete(function(e, jqx){
    delete Q[jqx._id];
  });

  return {
    abortAll: function(){
      var r = [];
      $.each(Q, function(i, jqx){
        r.push(jqx._id);
        jqx.abort();
      });
      return r;
    }
  };

})();

返回一个具有单个函数的对象,该对象可用于在需要时添加更多功能。


同样重要的是:假设您想要注销,并且正在使用计时器生成新的请求:因为会话数据会随着每次新的引导而更新(也许您可以告诉我说的是Drupal,但这可能是任何使用会话的站点)……我必须通过搜索和替换我所有的脚本,因为我有大量的东西在不同的情况下运行:全局变量在顶部:

var ajReq = [];
var canAj = true;
function abort_all(){
 for(x in ajReq){
    ajReq[x].abort();
    ajReq.splice(x, 1)
 }
 canAj = false;
}
function rmvReq(ranNum){
 var temp = [];
 var i = 0;
 for(x in ajReq){
    if(x == ranNum){
     ajReq[x].abort();
     ajReq.splice(x, 1);
    }
    i++;
 }
}
function randReqIndx(){
 if(!canAj){ return 0; }
 return Math.random()*1000;
}
function getReqIndx(){
 var ranNum;
 if(ajReq.length){
    while(!ranNum){
     ranNum = randReqIndx();
     for(x in ajReq){
    if(x===ranNum){
     ranNum = null;
    }
     }
    }
    return ranMum;
 }
 return randReqIndx();
}
$(document).ready(function(){
 $("a").each(function(){
    if($(this).attr('href').indexOf('/logout')!=-1){          
     $(this).click(function(){
    abort_all();                 
     });
    }
 })
});
// Then in all of my scripts I wrapped my ajax calls... If anyone has a suggestion for a 
    // global way to do this, please post
var reqIndx = getReqIndx();
if(reqIndx!=0){
ajReq[reqIndx] = $.post(ajax, { 'action': 'update_quantities', iids:iidstr, qtys:qtystr },  
function(data){
 //..do stuff
 rmvReq(reqIndx);
 },'json');
}

我已经更新了代码,使它为我工作

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(idx, jqXHR) {
        jqXHR.abort();
    });
    $(this).each(function(idx, jqXHR) {
        var index = $.inArray(jqXHR, $.xhrPool);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    });
};

$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = $.inArray(jqXHR, $.xhrPool);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    }
});

以下是如何在任何点击中连接它(如果您的页面放置了许多AJAX调用,并且您试图导航离开,则很有用)。

$ ->
    $.xhrPool = [];

$(document).ajaxSend (e, jqXHR, options) ->
    $.xhrPool.push(jqXHR)

$(document).ajaxComplete (e, jqXHR, options) ->
    $.xhrPool = $.grep($.xhrPool, (x) -> return x != jqXHR);

$(document).delegate 'a', 'click', ->
    while (request = $.xhrPool.pop())
      request.abort()

我扩展了mkmurray和SpYk3HH回答上面的xhrPool。abortAll可以中止所有给定url的挂起请求:

$.xhrPool = [];
$.xhrPool.abortAll = function(url) {
    $(this).each(function(i, jqXHR) { //  cycle through list of recorded connection
        console.log('xhrPool.abortAll ' + jqXHR.requestURL);
        if (!url || url === jqXHR.requestURL) {
            jqXHR.abort(); //  aborts connection
            $.xhrPool.splice(i, 1); //  removes from list by index
        }
    });
};
$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR); //  add connection to list
    },
    complete: function(jqXHR) {
        var i = $.xhrPool.indexOf(jqXHR); //  get index for current connection completed
        if (i > -1) $.xhrPool.splice(i, 1); //  removes from list by index
    }
});
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    console.log('ajaxPrefilter ' + options.url);
    jqXHR.requestURL = options.url;
});

除了abortAll现在可以选择接受url作为参数并只取消对该url的挂起调用之外,其他用法是相同的


把我的帽子扔进去。提供针对xhrPool数组的中止和删除方法,并且不容易出现ajaxSetup覆盖问题。

/**
 * Ajax Request Pool
 * 
 * @author Oliver Nassar <onassar@gmail.com>
 * @see    http://stackoverflow.com/questions/1802936/stop-all-active-ajax-requests-in-jquery
 */
jQuery.xhrPool = [];

/**
 * jQuery.xhrPool.abortAll
 * 
 * Retrieves all the outbound requests from the array (since the array is going
 * to be modified as requests are aborted), and then loops over each of them to
 * perform the abortion. Doing so will trigger the ajaxComplete event against
 * the document, which will remove the request from the pool-array.
 * 
 * @access public
 * @return void
 */
jQuery.xhrPool.abortAll = function() {
    var requests = [];
    for (var index in this) {
        if (isFinite(index) === true) {
            requests.push(this[index]);
        }
    }
    for (index in requests) {
        requests[index].abort();
    }
};

/**
 * jQuery.xhrPool.remove
 * 
 * Loops over the requests, removes it once (and if) found, and then breaks out
 * of the loop (since nothing else to do).
 * 
 * @access public
 * @param  Object jqXHR
 * @return void
 */
jQuery.xhrPool.remove = function(jqXHR) {
    for (var index in this) {
        if (this[index] === jqXHR) {
            jQuery.xhrPool.splice(index, 1);
            break;
        }
    }
};

/**
 * Below events are attached to the document rather than defined the ajaxSetup
 * to prevent possibly being overridden elsewhere (presumably by accident).
 */
$(document).ajaxSend(function(event, jqXHR, options) {
    jQuery.xhrPool.push(jqXHR);
});
$(document).ajaxComplete(function(event, jqXHR, options) {
    jQuery.xhrPool.remove(jqXHR);
});

最好使用独立代码.....

var xhrQueue = []; 

$(document).ajaxSend(function(event,jqxhr,settings){
    xhrQueue.push(jqxhr); //alert(settings.url);
});

$(document).ajaxComplete(function(event,jqxhr,settings){
    var i;   
    if((i=$.inArray(jqxhr,xhrQueue)) > -1){
        xhrQueue.splice(i,1); //alert("C:"+settings.url);
    }
});

ajaxAbort = function (){  //alert("abortStart");
    var i=0;
    while(xhrQueue.length){ 
        xhrQueue[i++] .abort(); //alert(i+":"+xhrQueue[i++]);
    }
};

做一个池的所有ajax请求和中止他们.....

var xhrQueue = []; 

$(document).ajaxSend(function(event,jqxhr,settings){
    xhrQueue.push(jqxhr); //alert(settings.url);
});

$(document).ajaxComplete(function(event,jqxhr,settings){
    var i;   
    if((i=$.inArray(jqxhr,xhrQueue)) > -1){
        xhrQueue.splice(i,1); //alert("C:"+settings.url);
    }
});

ajaxAbort = function (){  //alert("abortStart");
    var i=0;
    while(xhrQueue.length){ 
        xhrQueue[i++] .abort(); //alert(i+":"+xhrQueue[i++]);
    }
};

我发现对多个请求来说太简单了。

步骤1:在页面顶部定义一个变量:

  xhrPool = []; // no need to use **var**

step2:在所有ajax请求中设置beforeSend:

  $.ajax({
   ...
   beforeSend: function (jqXHR, settings) {
        xhrPool.push(jqXHR);
    },
    ...

第三步:在任何需要的地方使用它:

   $.each(xhrPool, function(idx, jqXHR) {
          jqXHR.abort();
    });

var Request = {
    List: [],
    AbortAll: function () {
        var _self = this;
        $.each(_self.List, (i, v) => {
            v.abort();
        });
    }
}
var settings = {
    "url": "http://localhost",
    success: function (resp) {
        console.log(resp)
    }
}

Request.List.push($.ajax(settings));

每当您想要中止所有ajax请求时,只需调用这一行

Request.AbortAll()

有一个虚拟的解决方案,我用它来中止所有ajax请求。这个解决方案是重新加载整个页面。如果您不喜欢为每个ajax请求分配ID,并且在for-loop中进行ajax请求,则此解决方案很好。这将确保所有ajax请求都被杀死。

location.reload();

这里是一个复制过去的函数,刷新所有的ajax调用。 fillCompteList()和fetchAll()必须返回ajax对象:

function fillCompteList() {
   return $.ajax({
            url: 'www.somewhere.com' ,
            method: 'GET',
            success: function(res){
            ...
          });

然后用这个

var xhrPool = [fillCompteList(inisial), fetchAll(params)] ;//old
function refrechAllUsing(SOME , params){
    xhrPool.forEach(function(request){
        request.abort();
    });
    xhrPool = [fillCompteList(SOME), fetchAll(params)]//new with other parameters
    Promise.all(xhrPool).then(() => {
        $('#loadding').undisplay();//remove the loadding screen 

    }).catch(() => {
        warning("Some problem happened");
        $('#loadding').undisplay();//remove the loadding screen 
    });
}