[英]Jquery multiple Ajax Request in array loop
如何通过一个发出多个ajax请求,我有一个大数据数组,并且循环遍历该数组,因此在每个循环中我都需要向服务器发出ajax请求,但是我只想在最后一个请求完成后才发出请求
现在是我的代码:
// 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
});
}
您可以使用async.js进行多个异步操作。
https://caolan.github.io/async/
例子:
async.parallel([
function(callback) { ... },
function(callback) { ... }
], function(err, results) {
// optional callback
});
async.series([
function(callback) { ... },
function(callback) { ... }
]);
我会用递归函数解决您的问题。
脚步:
码:
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);
});;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.