我想我已经看过了所有关于这方面的问题。
我有一个使用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张发票,我会得到控制台文本"starting xxx“3次,然后是"done xxx”4次。
如下所示:
starting 243
starting 663
starting 823
done 243
done 663
done 823而我想要的是
starting 243
done 243
starting 663
done 663
starting 823
done 823如有任何建议,我们将不胜感激。我要扯掉我那有限的头发了。
克里斯
发布于 2021-10-14 12:55:43
呼叫成功
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(); // starthttps://stackoverflow.com/questions/69569771
复制相似问题