我有一个问题,当提交表单时,所有活跃的ajax请求失败,并触发错误事件。
如何在jQuery中停止所有活动ajax请求而不触发错误事件?
我有一个问题,当提交表单时,所有活跃的ajax请求失败,并触发错误事件。
如何在jQuery中停止所有活动ajax请求而不触发错误事件?
当前回答
下面的代码片段允许您维护一个请求列表(池),并在需要时中止它们。最好放在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>
其他回答
安迪的代码有一些问题,但它给了我一些很好的想法。第一个问题是,我们应该弹出任何成功完成的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,它都不工作。
以下是我目前正在使用的方法。
$.xhrPool = [];
$.xhrPool.abortAll = function() {
_.each(this, function(jqXHR) {
jqXHR.abort();
});
};
$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
}
});
注意:_。js中的每一个都存在,但显然不是必需的。我只是懒惰,我不想把它改为$.each()。8页
我发现对多个请求来说太简单了。
步骤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();
});
我已经更新了代码,使它为我工作
$.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);
}
}
});
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()