有两种基本方法可以做到这一点:
使用 Promise 将多个 ajax 调用链接在一起。链接过程将强制执行顺序操作,因此一个完成,然后启动下一个。
在 ajax 调用的成功处理程序中,启动下一个 ajax 调用(您的第三个选项)。
如果不同的 ajax 调用实际上并不相互依赖,您也可以并行启动它们,然后仅序列化结果。这样可以大大加快端到端时间。
或者,正如其他人所建议的那样,如果您可以修改您的 Web 服务,以便可以在一次 ajax 调用中传递多个请求,那么您可以通过一次 ajax 调用请求所有数据,服务器将立即返回所有数据.
对于第一个选项,这是一个使用 Promise 序列化 ajax 调用的示例:
Sequential function calls in javascript
// serialize all requests
function A() {
var p = $.get(url).then(function(data) {return $.post(url)});
for (var i = 1; i < 5; i++) {
// chain four more pairs of requests onto the original promise
p = p.then(function() {return $.get(url)})
.then(function(data) {return $.post(url)});
}
// return the promise so callers can monitor when A() is done
return p;
}
function B() {
// sequence these three operations one after the other
return ($.get(url)
.then(function(data) {return $.post(url + x)})
.then(update_dropdown)
);
}
// run them both, one after the other
A().then(B);
对于第二个选项,您不能使用for 循环,因为(正如您已经知道的那样,它只是一次启动所有 ajax 调用)。相反,您重构循环,以便从成功处理程序启动下一次迭代。这是第二个选项的示例,该示例取自我周围的其他一些代码:
(function() {
var checked = $('.check_box_ping:checked');
var index = 0;
function next() {
if (index < checked.length ) {
var item = checked.eq(index++);
// use item here for your post
$.post({...}, function(response) {
// do your normal handling of the response here
...
// now kick off the next iteration of the loop
next();
});
}
}
next();
})();
这里有几个其他的例子:
behavior of ajax call inside a for loop
Wait for AJAX to finish before proceeding with the loop?
While loop with jQuery async AJAX calls