简体   繁体   English

延迟 jquery ajax

[英]Deferred jquery ajax

I've looked through all the issues on this, I think.我想我已经浏览了所有关于此的问题。

I have a function which uses jquery to update a record via ajax.我有一个函数,它使用 jquery 通过 ajax 更新记录。 I need to change it to do them and wait for each one to finish.我需要更改它以执行它们并等待每个完成。

I've been reading about $.Deferred and have tried to implement, but the code still doesn't wait.我一直在阅读$.Deferred并尝试实现,但代码仍然没有等待。 I understand that ajax is asynchronous and I don't want to change that as such, but I do want it to wait, as the code outputs messages and I need them in order.我知道 ajax 是异步的,我不想改变它,但我确实希望它等待,因为代码输出消息并且我需要它们。

My code is as such:我的代码是这样的:

//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();

}

It must be so close, but I guess I've got something missing or in the wrong place.它一定很近,但我想我遗漏了什么或在错误的地方。 The text from the resulting export does appear where it should, but if (for example) I select 3 invoices, I get the console text of "starting xxx" 3 times, and then the "done xxx" four times.结果导出的文本确实出现在它应该出现的位置,但是如果(例如)我选择了 3 张发票,我会得到 3 次“开始 xxx”的控制台文本,然后是“完成 xxx”四次。

Like this:像这样:

starting 243
starting 663
starting 823
done 243
done 663
done 823

Whereas what I want is而我想要的是

starting 243
done 243
starting 663
done 663
starting 823
done 823

Any advise would be lovingly appreciated... I'm tearing my limited hair out.任何建议将不胜感激......我正在撕掉我有限的头发。

Chris克里斯

Call in Success呼叫成功

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM