来到这里寻求类似的问题,并决定回答,即使对于其他最终可能遇到相同问题的人来说已经很晚了。
我相信您需要的是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一起使用,以响应您的数据类型为“文本”的数据类型,那么您将在控制台上看到的是此输出。(1-是console.log来自
SendData(),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!
实际上,甚至在调用重载函数时,即使在小提琴上(请求有错误),您也可以看到它。如果您使用“
ajaxComplete”,则jQuery内部的重载函数.click()函数将在很早之前被调用。但是,如果使用“ ajaxStop”并在触发“
ajaxStop”事件时调用重载函数,则在所有请求完成后将调用重载函数。
我不知道小提琴是否会在一段时间后消失,所以我也会在没有控制台日志的情况下发布在这里所做的更改:
$(".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”事件如何延迟触发,直到所有正在进行的请求完成(或至少完成并发生错误)为止…



