有没有办法在没有request对象句柄的情况下全局中止所有Ajax请求?
我这样问的原因是,我们有一个相当复杂的应用程序,我们使用setTimeOut()在后台运行许多不同的Ajax请求。如果用户单击某个按钮,我们需要暂停所有正在进行的请求。
发布于 2010-08-11 16:05:11
如果没有跟踪所有活动的Ajax请求的句柄,则不能中止这些请求。
但是,如果您正在跟踪它,那么您可以通过循环遍历处理程序并在每个处理程序上调用.abort()
来实现。
发布于 2012-12-17 15:22:58
您可以使用以下脚本:
// $.xhrPool and $.ajaxSetup are the solution
$.xhrPool = [];
$.xhrPool.abortAll = function() {
$(this).each(function(idx, jqXHR) {
jqXHR.abort();
});
$.xhrPool = [];
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = $.xhrPool.indexOf(jqXHR);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
}
});
在http://jsfiddle.net/s4pbn/3/上查看结果。
发布于 2016-03-25 22:47:33
以下是一个相关问题的答案,它对我很有效:
https://stackoverflow.com/a/10701856/5114
注意第一行,@grr说:“使用ajaxSetup是不正确的”
如果你想自己调用window,而不是像他们那样使用window.onbeforeunload
,你可以修改他的回答,将你自己的函数添加到window中。
// Most of this is copied from @grr verbatim:
(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});
});
// I changed the name of the abort function here:
window.abortAllMyAjaxRequests = function() {
$.each(xhrPool, function(idx, jqXHR) {
jqXHR.abort();
});
};
})(jQuery);
然后,您可以调用window.abortAllMyAjaxRequests();
将它们全部中止。确保将.fail(jqXHRFailCallback)
添加到ajax请求中。回调将以textStatus
的形式'abort‘,这样你就知道发生了什么:
function jqXHRFailCallback(jqXHR, textStatus){
// textStatus === 'abort'
}
https://stackoverflow.com/questions/3456427
复制相似问题