如何一次发出多个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
});
}
最佳答案
我会用递归函数解决你的问题。
步骤:
- 创建一个将接收一个参数的递归函数
- 如果数组长度大于 0,则继续执行函数体
- 移位数组(从数组中删除第一项并将其存储到变量中)
- 调用我们的函数并使用提供的参数执行 AJAX 调用,并传递我们的数组
- 当 AJAX 调用完成时,调用我们的递归函数并将数组传递给它
代码:
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);
});;
}
关于javascript - Jquery数组循环中的多个Ajax请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52079500/