如何使用两个Ajax Get请求只显示一条警报消息



我使用两个Ajax Get请求,每个请求都有一个if条件,如果不适用,我必须保存原因并在一条警报消息中显示。但我显示了两个警报,每个警报对应一个get请求。这是我的代码:

var errorMessage = "";
$.get(url, function (responseGET) {
var responseGETHtml = $(responseGET).find(".data-table tbody").html();
console.log("responseGETHtml", responseGETHtml, typeof responseGETHtml);
var rowCount = $(responseGETHtml).filter("tr").length;
if (rowCount > 1) {
errorMessage +=
"There is more than one result for invoice #" + invoiceId + "n";
}
});
var url2 = "/einnahmen/" + customerId;
url = url2.trim();
$.get(url2, function (responseGET) {
var responseGETHtml2 = $(responseGET).find(".data-item-form form.form");


if (brutto < csvBrutto) {
errorMessage += "Brutto of csv is bigger than Brutto in table" + "n";
}
if (errorMessage != "") {
alert(errorMessage);
} else {
responseGETHtml
.find(".form-choice .forminput-zahlungsweise")
.prop("checked", true)
.val("Überweisung");
$.post({
url: "/einnahmen/?filter[rechnung_nr]=" + invoiceId,
data: responseGETHtml.serialize(),
success: function (responsePOST) {
alert($(responsePOST).find(".message").text());
},
dataType: "html"
});
}
});

如何只显示一条包含所有错误的警报消息?

我的想法是使用Promises,尤其是Promise.all((。

  1. 让我们在promise中转换每个请求,该promise将解析请求的结果,但使用errorMessage作为参数
  2. 对这些Promise使用Promise.all((,当两个请求都得到解决时,这个新的Promise就会得到解决
  3. 如果一个或多个请求出现错误,请加入错误消息(如果不恢复代码(
const request1 = new Promise(resolve => {
$.get(url, function(responseGET) {
var responseGETHtml = $(responseGET).find(".data-table tbody").html();
console.log("responseGETHtml", responseGETHtml, typeof responseGETHtml);
var rowCount = $(responseGETHtml).filter("tr").length;
const errorMessage = rowCount > 1 ? `There is more than one result for invoice #${invoiceId}` : '';
resolve(errorMessage);
});
});
var url2 = "/einnahmen/" + customerId;
url = url2.trim();
const request2 = new Promise(resolve => {
$.get(url2, function(responseGET) {
var responseGETHtml2 = $(responseGET).find(".data-item-form form.form");
const errorMessage = brutto < csvBrutto ? 'Brutto of csv is bigger than Brutto in table' : '';
resolve(errorMessage);
});
});
Promise.all([request1, request2]).then(errorMessages => {
// this code is executed when both request has resolved
// has at least one request resolved with an error message ?
const hasError = errorMessages.some(error => error != '');
if (hasError) {
alert(errorMessages.join('n'));
} else {
// this code is executed when both request has resolved with no error.   
responseGETHtml
.find(".form-choice .forminput-zahlungsweise")
.prop("checked", true)
.val("Überweisung");
$.post({
url: "/einnahmen/?filter[rechnung_nr]=" + invoiceId,
data: responseGETHtml.serialize(),
success: function(responsePOST) {
alert($(responsePOST).find(".message").text());
},
dataType: "html"
});
}

});

最新更新