如何通过一个发出多个ajax请求,我有一个很大的数据数组,并且循环遍历该数组,所以在每个循环中我都需要向服务器发出ajax请求,但是我只想在最后一个请求完成后才发出请求< / p>
现在这是我的代码:
// This is loop for BigData
length = BigArray.length;
for (i = 0; i < length; i++) {
token = BigArray[i][0];
name = titleCase(BigArray[i][1]);
ajaxRequest(token, name);
}
function ajaxRequest(token, title) {
$.post(APP_URL + "/message/send", {
"_token": Laraveltoken,
title: title,
token: token
}, function(data, status) {
//When Done start next request
});
}
答案 0 :(得分:0)
您可以使用 async.js 进行多个异步操作。
https://caolan.github.io/async/
示例:
async.parallel([
function(callback) { ... },
function(callback) { ... }
], function(err, results) {
// optional callback
});
async.series([
function(callback) { ... },
function(callback) { ... }
]);
答案 1 :(得分:0)
我将通过递归函数解决您的问题。
步骤:
代码:
function myRecursiveFunction(myArray){
if(myArray.length == 0) return;
//remove first item of an array then store it into variable item
var item = myArray.shift();
//call our method which will execute AJAX call to server
ajaxRequest(item[0], titleCase(item[1]), myArray);
}
function ajaxRequest(token, title, myArray) {
$.post(APP_URL + "/message/send", {
"_token": Laraveltoken,
title: title,
token: token
}, function(data, status) {
//When Done start next request
}).always(function(){
//call our recursive function
myRecursiveFunction(myArray);
});;
}