jQuery数组循环中的多个Ajax请求 [英] Jquery multiple Ajax Request in array loop
本文介绍了jQuery数组循环中的多个Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何通过一个发出多个ajax请求,我有一个很大的数据数组,并且循环遍历该数组,因此在每个循环中我都需要向服务器发出ajax请求,但我只想在最后一个请求完成后才发出请求
How can make multiple ajax requests on by one i have a big array of data and i loop through that array and in every loop i need to make ajax request to server but i want to make request only when last request is finsihed
现在这是我的代码:
// 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
});
}
推荐答案
我将通过递归函数解决您的问题.
I would solve your problem with recursive function.
步骤:
- 创建一个将接收一个参数的递归函数
- 如果数组长度大于0,则继续使用函数正文
- Shift数组(从数组中删除第一项并将其存储到变量中)
- 调用我们的函数并使用提供的参数执行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);
});;
}
这篇关于jQuery数组循环中的多个Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文