簡體   English   中英

等待異步調用無法與Ajax一起使用

[英]Waiting on asynchronous call not working with ajax

我使用了deferred來等待大約兩個功能完成(它們提供了模板並顯示結果),然后再提供模板中存在的選擇。

當顯示選項卡時,我會這樣做。

var notAssociateContact = getNotAssociateContact();
var associateContact = getAssociateContact();

$.when(notAssociateContact, associateContact).then(assignLocationToSelector($("select[name=locationIds\\[\\]]")));

function getNotAssociateContact() {

    var deferred = $.ajax({
        type: "GET",
        url: "http://localhost:8080/rest/contacts/notassociatedto/" + $("#lodgerId").val(),
        success: function(data, status, jqXHR) {

            $("#lodgerContactAvailableDivTemplate").empty();
            if (data.length != 0) {
               $("#lodgerContactAvailableDivTemplate").append(templateLodgerContactAvailable(data));
                $('#lodgerContactAvailableTableResult').bootstrapTable();
            }
        },
        error: function(jqXHR, status) {
            // error handler
            alert("error " + jqXHR + " -  " + status);
        }
    }).then(function(response) {
        // optional callback to handle this response 
    });
    return deferred;

}


function getAssociateContact() {
    var deferred = $.ajax({
        type: "GET",
        url: "http://localhost:8080/rest/lodgers/" + $("#lodgerId").val() + "/contacts",
        success: function(data, status, jqXHR) {
            $("#lodgerContactDivTemplate").empty();
            if (data.length != 0) {
                $("#lodgerContactDivTemplate").append(templateLodgerContact(data));
                $('#lodgerContactTableResult').bootstrapTable();
                //  $('#lodgerContactTableResult tr').bind("dblclick", null, contactReferenceSelectedRow);
            }
        },
        error: function(jqXHR, status) {
            // error handler
            alert("error " + jqXHR + " -  " + status);
        }
    }).then(function(response) {
        // optional callback to handle this response 
    });
    return deferred;
}

我沒有收到任何錯誤,但是assignLocationToSelector與運行時不一樣。 選擇為空。

在控制台中,如果我運行

assignLocationToSelector($("select[name=locationIds\\[\\]]"));

選擇已正確送入。

當我調試並到達$ .when時,我看到然后兩個ajax調用正在等待...

因此,似乎延遲存在問題。

您的$.when().then()需要傳遞一個函數引用。 您正在立即調用一個函數,然后傳遞該返回結果。 那將立即執行該函數,而不是允許$.when()稍后調用它。

從此更改$.when()語句:

$.when(notAssociateContact, associateContact).then(assignLocationToSelector($("select[name=locationIds\\[\\]]")));

對此:

$.when(notAssociateContact, associateContact).then(function() {   
   assignLocationToSelector($("select[name=locationIds\\[\\]]"));
});

暫無
暫無

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

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