[英]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.