[英]Execute code after all the promises have been resolved with Jquery
我似乎很难找出如何在代码中使用when函数。 我希望实现的是在完成所有ajax请求后的window.location.reload
。
如果将window.location.reload
放在“每个”循环之后,那么我所有的AJAX请求都将被中止。
$('.removeSelected').click(function() {
if (confirm('Are you sure you will continue?')) {
$('.container-fluid :input:checked').each(function () {
var recordId = $(this).data("id");
// Jquery remove it
$.ajax({
method: "GET",
url: "/controllers/lines.asp",
data: { recordId: recordId }
}).done(function() {
console.log('done');
});
});
// window location reload here
}
});
您的逻辑顺序似乎有缺陷。 我认为您想要做的是收集所有记录,然后发送一个请求。 请求完成后,您将重新加载。
$('.removeSelected').click(function() {
if (confirm('Are you sure you will continue?')) {
//prepare an array for records
var records = [];
$('.container-fluid input:checked').each(function () {
//add the id
records.push($(this).data("id"));
});
//make the request
$.ajax({
method: "GET",
url: "/controllers/lines.asp",
data: records
}).done(function() {
//when successful, reload the page
window.location.reload();
});
});
};
});
我不确定您是否要在成功或完成时重新加载(失败时也会重新加载)。
获取要删除的元素数量
$('.container-fluid :input:checked').size();
每次调用完成时,都增加一个单独的总数。 当总数与计数匹配时,请重新加载页面。
您需要将所有承诺传递给“何时”,以便它可以等待所有承诺都得到解决。
为此,您可以将$.ajax
返回的所有promise放入数组中,并将其传递给$.when
:
$('.removeSelected').click(function() {
if (confirm('Are you sure you will continue?')) {
var promises = [];
$('.container-fluid :input:checked').each(function () {
var recordId = $(this).data("id");
// Jquery remove it
promises.push($.ajax({
method: "GET",
url: "/controllers/lines.asp",
data: { recordId: recordId }
})
.done(function() {
console.log('done');
}));
});
// use apply to pass an array instead list of parameters
$.when.apply($, promises).then(function() {
// all the promises have been resolved
window.location.reload();
}
});
我赞成冒犯性的观点,即一次发送全部而不是每条记录都发出请求会更有效。
但是,如果由于任何原因您不想更改服务器端代码,则需要确定何时完成所有请求。 您可以使用Promise实现此目标。
如果您对此没有太多经验,那么下面的代码应为您提供有关如何在不使用promise的情况下实现预期行为的想法:
$('.removeSelected').click(function() {
if (confirm('Are you sure you will continue?')) {
var $containerFluidElements = $('.container-fluid :input:checked');
var numberOfRequestsPending = $containerFluidElements.length;
$containerFluidElements.each(function () {
var recordId = $(this).data("id");
$.ajax({
method: "GET",
url: "/controllers/lines.asp",
data: { recordId: recordId }
}).done(function() {
numberOfRequestsPending -= 1;
if(numberOfRequestsPending == 0)
{
window.location.reload();
}
});
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.