用户点击将发起ajax请求
无法知道将发送多少请求
我尝试了ajaxComplete,但它不起作用,我认为它在页面加载后无法检测到ajax。
function ajax1() {
$.ajax({
url: 'getCount.php',
type: 'GET',
dataType: 'html',
success: function (data) {
var count = parseInt(data);
for (var i = 0; i < count; i++) {
ajax2();
}
}
});
}
function ajax2() {
$.ajax({
url: 'getCount2.php',
type: 'GET',
dataType: 'html',
success: function (data) {
var count = parseInt(data);
for (var i = 0; i < count; i++) {
ajax3();
}
}
});
}
function ajax3() {
$.ajax({
url: 'ajax3.php',
type: 'GET',
dataType: 'html',
success: function (data) {
//do something
}
});
}
$(document).ajaxComplete(function (event, xhr, settings) {
alert('Complete');
});
最佳答案
更新:非常好的阅读 promise :Promises cookbook
正常的方法是使用 $.ajax
函数返回的 promise 。
更改您的函数以返回 .ajax
调用的结果:
function ajax1(..) {
return $.ajax(...)
}
然后使用 $.when
在所有 Promise 都得到解决时使新的 Promise 得到解决。
$.when([ajax1(), ajax2(), ajax3()]).then(function() { alert('all complete') })
但是,在更复杂的情况下(如您的情况),您需要动态存储对所有 promise 的引用,并且仅在添加所有 promise 后才调用 $.when
。
例如,您可以创建 Promise 数组,一个用于 ajax2
调用,一个用于 ajax3
调用。
var ajax2calls = [], ajax3calls=[]
function ajax1() {
return $.ajax({
url: 'getCount.php',
type: 'GET',
dataType: 'html',
success: function (data) {
var count = parseInt(data);
for (var i = 0; i < count; i++) {
ajax2calls.push(ajax2());
}
$.when(ajax2calls).then(function() {
$.when(ajax3calls).then(function() {
alert('all done')
}
})
}
});
}
此外,您可能需要考虑使用 Bluebird Promise 库,因为它提供了比常规 Promise/A 或 Promise/A+ 更丰富的 API。检查map
、settle
、all
方法等。
关于javascript - 当所有ajax完成时如何触发函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32426753/