设置
<小时/>我有一个表单,它使用一系列复选框来确定页面上选定的数字:
它的作用是在选择时,它会调用一个 Controller ,该 Controller 将保存选择并根据其当前数据返回新的检查金额。
代码如下所示
$('#myId').('click', '.selectorClass input', function() {
const inputCheckBox = this;
inputCheckBox.disabled = true;
$(inputCheckBox).addClass('disabled-checkbox')
$.ajax({
method: "POST",
url: "@(Url.Action<MyController>(c => c.MyEndPoint(Model.ItemId, null)))",
data: {
"boxWasChecked": inputCheckBox.checked
}
}).done(function (data) {
UpdateFields(inputCheckBox, data); //this would update the column footer and 'Total Quantity' field below
}).fail(function (data) {
// error check and handle here
}).always(function(data) {
inputCheckBox.disabled = false;
$(inputCheckBox).removeClass('disabled-checkbox')
});
});
一次选择一个时,这非常有效,甚至在选择多个时通常也有效。
<小时/>问题
<小时/>当用户非常快速地选择它们时,有时最后一个完成的请求不是最后一个进入/从 Controller 端的数据库中获取数据的请求,因此它会带回错误的数学总计。
参见下图,其中数学应该为 11(请记住,它是添加每个框的值而不是选中的框的数量),但报告为 6。
如果我选择最后一个复选框,它将正确报告 12,因为它具有用于调用的所有正确数据。
我陷入困境的部分
<小时/>我认为我需要以某种方式制作一个 ajax 调用列表,然后仅在有一个请求在其之后添加或它前面的所有其他请求已完成时才取消该请求。我不知道如何通过 ajax 调用来做到这一点。
我已经玩过 promises/Fetch API并试图让它工作,但可以得到添加到 Promise.all[myListOfAjaxCalls]
中的堆栈的 promise 。
我正在努力实现的代码摘要
var listOfPromiseCalls = []
$('#myId').('click', '.selectorClass input', function() {
// my checkbox is clicked
listOfPromiseCalls.push(myAjaxCall/myPromise)
// Psudeo code
// begin request if it is the only one in the list
// else
// kick off other requests that are in existing list infront of it
// if other requests finish before another input is clicked, begin this request
});
最佳答案
我认为通过创建包含所有请求的列表,您的路径是正确的,但由于您使用 jQuery 进行异步调用,因此您应该使用 $.when
operator等待所有请求完成。 Promise.all
不起作用,因为 $.ajax
没有实现与 new Promise()
相同的接口(interface),所以你需要使用 jQuery 运算符来处理它。
您可以如上所述使用包含所有异步调用的列表,然后执行以下操作:
$.when(...listOfPromiseCalls)
.done((...allResponses) => {
// do something
})
.catch(errors => {
// handle errors
});
请注意,我使用 es6 中的扩展运算符来将所有请求扩展到 when
并聚合所有响应 在响应列表中。
关于扩展语法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
如果你不会使用es6语法,我建议你学习并使用js函数的apply
方法,它会给出相同的结果。
关于javascript - 仅当列表中添加了 ajax 请求时才调用 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60175628/