繁体   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