[英]Deferred jquery ajax
我想我已經瀏覽了所有關於此的問題。
我有一個函數,它使用 jquery 通過 ajax 更新記錄。 我需要更改它以執行它們並等待每個完成。
我一直在閱讀$.Deferred
並嘗試實現,但代碼仍然沒有等待。 我知道 ajax 是異步的,我不想改變它,但我確實希望它等待,因為代碼輸出消息並且我需要它們。
我的代碼是這樣的:
//do the export:
function doExport(id) {
var exportComplete = $.Deferred();
var exportPromise = $.ajax({
type: "POST",
url: "import.php",
dataType: "json",
data: { id: id }
});
exportPromise.done(function(msg) {
//msg contains the text from the import
exportComplete.resolve(msg);
});
return exportComplete.promise();
}
//export all ticked items (from a list)
function importInvoices() {
var checked = new Array;
$('#apiCall').html("");
//put all checked items into an array (id corresponds to a PK in the db)
$("input[name=selectedRow]:checked").each(function(num,row) {
checked.push($(row).data('id'));
});
//loop through each checked item
$(checked).map(function(num, id) {
console.log("starting " + id) ;
var prom = doExport(id).then(function(result) {
console.log("done " + id);
$('#apiCall').html($("#apiCall").html() + result.messages);
});
});
$("#pleaseWaitContainer").hide();
}
它一定很近,但我想我遺漏了什么或在錯誤的地方。 結果導出的文本確實出現在它應該出現的位置,但是如果(例如)我選擇了 3 張發票,我會得到 3 次“開始 xxx”的控制台文本,然后是“完成 xxx”四次。
像這樣:
starting 243
starting 663
starting 823
done 243
done 663
done 823
而我想要的是
starting 243
done 243
starting 663
done 663
starting 823
done 823
任何建議將不勝感激......我正在撕掉我有限的頭發。
克里斯
呼叫成功
const checked = $("input[name=selectedRow]:checked").map(function() {
return $(this).data('id'))
}).get()
const load = function() {
$.ajax({
url: `/someprocess.php?id=${checked.shift()}&otherparm=bla`,
success: function() {
if (checked.length > 0) load()
}
})
}
if (checked.length > 0) load(); // start
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.