我有一个问题,当提交表单时,所有活跃的ajax请求失败,并触发错误事件。
如何在jQuery中停止所有活动ajax请求而不触发错误事件?
我有一个问题,当提交表单时,所有活跃的ajax请求失败,并触发错误事件。
如何在jQuery中停止所有活动ajax请求而不触发错误事件?
当前回答
做一个池的所有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++]);
}
};
其他回答
这里是一个复制过去的函数,刷新所有的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
});
}
每次你创建一个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页
我已经更新了代码,使它为我工作
$.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);
}
}
});
下面的代码片段允许您维护一个请求列表(池),并在需要时中止它们。最好放在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>