如何总结多个Ajax调用,
我在for循环中编写了ajax方法,因为我需要得到多个结果,
for (i = 0; i < invoice_ids.length; i++) {
$.ajax({
url: "payments/getInvoiceAmount",
method: "post",
dataType: 'json',
data: {"amount_tds": amount_tds, "invoice_id":invoice_ids[i]},
success: function(response) {
//need get the sum of response
}
});
}
上面的ajax方法给出了多个结果,结果就像
[{"invoice_amount":"1000"}]
[{"invoice_amount":"1000"}]
[{"invoice_amount":"1000"}]
[{"invoice_amount":"1000"}]
[{"invoice_amount":"1000"}]
如何获得 invoice_amount:5000
等输出答案 0 :(得分:0)
您可以尝试以下
// Create an array of promises
var promises = [];
for (i = 0; i < invoice_ids.length; i++) {
promises.push(performAction(amount_tds, invoice_ids[i]));
}
// Iterate over the responses and calcuate the sum
Promise.all(promises).then((responses) => {
var sum = responses.reduce((a,c) => a + c.reduce((acc, b) => acc + parseFloat(b.invoice_amount), 0), 0);
});
// Create a function that sends ajax
function performAction(amount_tds, invoice_id) {
return $.ajax({
url: "payments/getInvoiceAmount",
method: "post",
dataType: 'json',
data: {"amount_tds": amount_tds, "invoice_id":invoice_ids}
});
}