在 Javascript 中发出顺序 POST 请求的最佳方法
Best approach to making sequential POST requests in Javascript
所以我有一个数组,其中包含需要作为 POST 请求的有效负载的一部分发送的数据。现在,这些需要按顺序进行,因为我需要显示特定的有效载荷,然后是结果(结果是在使用有效载荷发出 POST 请求后返回的响应),然后是下一个有效载荷,然后下一个结果等等,在我的页面上。我只是想知道完成任务的最佳方法是什么 this.So 这就是我目前的处理方式:
for (var i = 0; i < quotesList.length; i++) {
var response = $.ajax({
type: "POST",
url: url,
data: JSON.stringify(quotesList[i]),
success: add_to_page,
},
timeout: 300000,
error: function(){
console.log("Some Error!")
},
contentType: "application/json"
})
显然,这里出现的问题是无法保证顺序正确,而且我不太确定如何准确跟踪有效载荷,因为我试图将其添加为成功函数只让我得到最后一个元素(大概是最后一个被触发的请求)
你可以试试下面的方法。
let quotesListIndex = 0;
function sendAjaxCall() {
if (quotesListIndex < quotesList.length) {
var response = $.ajax({
type: "POST",
url: url,
data: JSON.stringify(quotesList[quotesListIndex++]),
success: function () {
//... Add code here
sendAjaxCall(); // Call the function again for next request
},
timeout: 300000,
error: function () {
console.log("Some Error!")
},
contentType: "application/json"
})
} else {
return;
}
}
添加一个全局变量来跟踪索引。并递归调用函数。一旦索引达到数组大小,然后 return 从函数。
所以我有一个数组,其中包含需要作为 POST 请求的有效负载的一部分发送的数据。现在,这些需要按顺序进行,因为我需要显示特定的有效载荷,然后是结果(结果是在使用有效载荷发出 POST 请求后返回的响应),然后是下一个有效载荷,然后下一个结果等等,在我的页面上。我只是想知道完成任务的最佳方法是什么 this.So 这就是我目前的处理方式:
for (var i = 0; i < quotesList.length; i++) {
var response = $.ajax({
type: "POST",
url: url,
data: JSON.stringify(quotesList[i]),
success: add_to_page,
},
timeout: 300000,
error: function(){
console.log("Some Error!")
},
contentType: "application/json"
})
显然,这里出现的问题是无法保证顺序正确,而且我不太确定如何准确跟踪有效载荷,因为我试图将其添加为成功函数只让我得到最后一个元素(大概是最后一个被触发的请求)
你可以试试下面的方法。
let quotesListIndex = 0;
function sendAjaxCall() {
if (quotesListIndex < quotesList.length) {
var response = $.ajax({
type: "POST",
url: url,
data: JSON.stringify(quotesList[quotesListIndex++]),
success: function () {
//... Add code here
sendAjaxCall(); // Call the function again for next request
},
timeout: 300000,
error: function () {
console.log("Some Error!")
},
contentType: "application/json"
})
} else {
return;
}
}
添加一个全局变量来跟踪索引。并递归调用函数。一旦索引达到数组大小,然后 return 从函数。