来到这里寻求类似的问题并决定回答,即使对于可能最终遇到同样问题的其他人来说已经很晚了。
我相信您需要的是 Ajax 全球事件。
请参阅 API 文档
尤其是这里;
全球活动
这些事件在文档上触发,调用任何可能正在侦听的处理程序。你可以像这样监听这些事件:
$(document).bind("ajaxSend", function(){
// You should use "**ajaxStop**" instead of "ajaxComplete" if there are more
// ongoing requests which are not completed yet
}).bind("ajaxStop", function(){
// call your reload function here
});
现在对于您的情况,如果您使用“ajaxStop”,而不是绑定“ajaxComplete”事件,这将在所有正在处理的 Ajax 请求完成时触发。
我在小提琴上复制粘贴了您的原始代码,并添加了我刚刚推荐的部分和一些日志。jsfiddle.net/Tt3jk/7/SendData2()
出于测试目的,我从您的第一个函数的成功事件中调用了一个类似的函数来模拟丑陋的异步请求场景。如果您在真实环境中测试此代码(或将 SendData2 与您的 url 一起放置,该 url 以您的数据类型“文本”响应,您应该在控制台上看到此输出。(1-是来自 console.logSendData()
和 2-来自SendData2()
):
1-sending...
waiting for all requests to complete...
1-success:!
2-sending...
waiting for all requests to complete...
1-done:
2-success:!
2-done:
completed now!
事实上,当你的 reload 函数被调用时,你甚至可以在小提琴上看到它(请求上有错误)。如果你使用“ajaxComplete”,你的 jQuery .click() 函数中的 reload 函数很早就被调用了。但是,如果您使用“ajaxStop”并在触发“ajaxStop”事件时调用reload函数,则在所有请求完成后会调用reload函数。
我不知道小提琴是否会在一段时间后消失,所以我也会在这里发布我所做的更改,而无需控制台日志:
$(".submit_button").click(function () {
popupMessage();
sendData(); //the ajax calls are all in here
// consider reloading somewhere else
});
$(document).bind("ajaxSend", function () {
console.log("waiting for all requests to complete...");
// ajaxStop (Global Event)
// This global event is triggered if there are no more Ajax requests being processed.
}).bind("ajaxStop", function () {
// maybe reload here?
location.reload();
});
function popupMessage() {
alert("Pop!");
}
function sendData() {
//a bunch of these:
$.ajax({
"dataType": "text",
"type": "POST",
"data": "temp",
"url": "your url here!",
"beforeSend": function (msg) {
console.log("1-sending...");
},
"success": function (msg) {
console.log("1-success!");
sendData2(); // again
},
"error": function (msg) {
console.log("1-error!");
}
}).done(function (msg) {
console.log("1-done!");
});
}
function sendData2() {
//a bunch of these:
$.ajax({
"dataType": "text",
"type": "POST",
"data": "temp",
"url": "your url here!",
"beforeSend": function (msg) {
console.log("2-sending...");
},
"success": function (msg) {
console.log("2-success!");
},
"error": function (msg) {
console.log("2-error!");
}
}).done(function (msg) {
console.log("2-done!");
});
}
PS。不确定从请求中发出另一个请求是否是一种好习惯,可能不是。但我把它放在那里是为了展示“ajaxStop”事件是如何延迟触发的,直到所有正在进行的请求都完成(或至少完成但有错误)......