在我的页面中,我调用了 15 个 ajax 请求。我还有一个按钮可以取消所有未决的 ajax 请求。 As per documentation , abort() 终止请求,如果它已经被发送。
现在,当我检查我的控制台时,即使在我点击取消按钮之后,我也会从 ajax 脚本中得到一些回复(我猜这些回复在我点击该按钮时已经发送了)。那么,我如何才能确保在按下取消按钮后不会收到回复?
You can check the script here (无法使用 jsfiddle,因为不确定如何发出 ajax 请求)。
JS代码
var xhrPool = [];
$(window).load(function(){
callAjax1();
});
$.ajaxSetup({
beforeSend: function(jqXHR) {
xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = xhrPool.indexOf(jqXHR);
if (index > -1) {
xhrPool.splice(index, 1);
}
}
});
var abortAjax = function () {
$.each(xhrPool, function(idx, jqXHR) {
if(jqXHR && jqXHR .readystate != 4){
jqXHR.abort();
}
});
console.log("All pending cancelled"); // Should not have any ajax return after this point
$.xhrPool = [];
};
$("#cancel-button").click(function (){
abortAjax();
});
function callAjax2(ajaxcallid){
console.log("Initiate ajax call " + ajaxcallid); // Should not have any ajax return after this point
$.ajax({
method: "POST",
url: "test.php"
})
.done(function( msg ) {
console.log(msg + ajaxcallid); // msg = "Ajax return for "
})
.fail(function( jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
}
function callAjax1(){
$.ajax({
method: "POST",
url: "test.php"
})
.done(function( msg ) {
for(var i = 0; i < 15; i++){
callAjax2(i);
}
})
.fail(function( jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
}
最佳答案
试试这个
$.each(xhrPool.slice(), function(idx, jqXHR) {
我想当你中止时,有些人又回来了,所以数组被弄乱了
这样你就可以使用数组的快照
当然,由于时间的原因,一两个可能仍然会偷偷溜走
关于javascript - 中止所有异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35193091/