gpt4 book ai didi

javascript - 等待异步调用不适用于ajax

转载 作者:行者123 更新时间:2023-12-02 15:22:44 24 4
gpt4 key购买 nike

我使用 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;
}

我没有收到任何错误,但 allocateLocationToSelector 与运行时不同。选择为空。

如果我运行在控制台中

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\\[\\]]"));
});

关于javascript - 等待异步调用不适用于ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com