簡體   English   中英

等待 function 內部的多個 ajax 調用?

[英]Await multiple ajax calls inside function?

上下文:制作 ajax 重頁,根據先前選擇器選擇的內容更改不同選擇器中的值。 致力於根據先前的條目制作“重新填充”選項。

When selector 1 is changed, an ajax call is made that populates both selector 2 and 3. Selector 1's options never change.


當您從先前的條目“重新填充”時,代碼首先更改選擇器 1 的值,然后激活選擇器 1 上的更改事件。

function repopulateFromEntry(event)  {
    // We want the children of the parent TR.
    // <tr>
    //  <td>...</td>
    //  ...
    //  <td><button></td>
    // <tr>
    let td_list = event.target.parentElement.parentElement.children;

    $('#selector1').val(td_list[0].innerHTML);
    $('#selector1').change();
    // Do other things that rely on prior to be finished
    // Problem is here.
};

選擇器 1 的更改事件如下所示。

async function executeAjax(url, success) {
    return await $.ajax({
        url: url,
        type: "GET",
        success: success
    });
}

$('#selector1').change(async function(e) {
    await executeAjax('api/selector2' + $("#selector1").val(), function() {
        // Set selector2 from ajax data
    });
    await executeAjax('api/selector3' + $("#selector1").val(), function() {
        // Set selector3 from ajax data
    });
});

根據 selector1 的值設置選擇器選項后,它會進入並為選擇器 2 和 3 選擇正確的值。


我的問題是選擇器 2 和 3 的值的重新選擇在選項完全填充到選擇器之前被調用,從而導致重新選擇失敗。

我顯然在 async/await/ajax 部分中遺漏了一些東西,以防止它在沒有完成兩個調用的情況下繼續,但我似乎看不出我的問題是什么。

好的,所以我對 $.ajax 調用使用了 async/await,然后在您的更改事件處理程序中,我使用了.then 方法來處理結果數據。 (也可以在事件處理程序中使用異步等待,但是由於您最初擁有它並且它不起作用,因此我選擇了 promise 代替)。

我很確定這應該可以,但如果不行,請告訴我控制台顯示的內容。

注意在設置每個選擇器的值之前,您可能需要 console.log 結果並提取您要查找的數據。 您可以在 .then 方法中執行此操作。

async function executeAjax(url) {

    let result;

    try { 
        result = await $.ajax({
            url: url,
            type: "GET"
        });

        return result;

    } catch (error) {
        console.log(error);
    }
}

$('#selector1').change(function(e) {

    executeAjax('api/selector2' + $("#selector1").val())
    .then((result) => { 
        // console.log(result);  <-- may need to find and pull the data you are looking for out of result
        // let myVal = result[?]['something'].orother;
        $("#selector2").val(result); 
    });

    executeAjax('api/selector3' + $("#selector1").val())
    .then((result) => {
        // console.log(result);  <-- may need to find and pull the data you are looking for out of result
        // let myVal = result[?]['something'].orother;
        $("#selector3").val(result);
    });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM