我使用jQuery有很多相同类型问题的实例。可能是因为我缺少一些基本知识(jQuery newb)。在我的$ .Ajax调用获取数据 - 成功:我根据返回的数据执行许多调用其他函数。呼叫需要按特定顺序进行,但这似乎不会发生。如果我有一个我写的另一个jQuery函数的调用,然后三行后面调用另一个函数(这取决于第一个函数调用中发生的一些事件),第二个调用首先发生。调试器在两个不同的$ .Ajax调用中多次设置,并且这种方式就是这样。我做错了什么?
顺便说一句 - 数据进入正常并填充我的表格和表格项目。根据请求我在下面发布代码 - 评论显示GetInventory需要在BuidlNav之前执行
$(document).ready(function () {
$('#searchNow').css('visibility', 'hidden'); //Hide Search Now button
$("#popup").css("display", "none");
$('#submit').prop('disabled', true);
$.ajax({
type: "POST",
url: "mypage.aspx/mywebmethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (states) {
var jsonCodes = JSON.parse(states.d);
for (var i in jsonCodes) {
$("#Select0").append(new Option(jsonCodes[i].regionname, jsonCodes[i].region_id));
}
var first = getUrlVars()["region"];
if (first) {
debugger;
$.fn.SetAllSelectors(reg);
$.fn.GetInventory(1, 10, reg, 'rank', 'asc'); //This should happen first
$.fn.BuildNav(); // This depends on GetInventory having been executed already.
}
else {
var myText = 'United States';
$("#Select0 option").filter(function () {
return $(this).text() == myText;
}).first().prop("selected", true);
$.fn.GetChildRegions("Select0");
}
}
});
}
);
答案 0 :(得分:2)
如果GetInventory
和BuildNav
也使用ajax,则需要更像这样的结构。在进行ajax调用时,数据是在不占用下一个命令行的情况下获取的,因此在第一个函数完成之前可能会调用第二个或第三个函数。
$.ajax({
type: "POST",
url: "mypage.aspx/mywebmethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (states) {
getInventoryAndBuildNav(states);
},
...
});
function getInventoryAndBuildNav(states){
$.ajax({
....
url: "mypage.aspx/getinventory",
success: function (inventory) {
$.fn.BuildNav();
},
...
});
}
实现此目的的最佳方法是为每个项目构建函数并允许传递回调方法。
以这种方式思考
$.ajax({
type: "POST",
url: "mypage.aspx/mywebmethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (states) {
//This will trigger second since we had to wait for the process to finish
alert('The Ajax call has been made, finished, and the data received');
}
});
//This will trigger FIRST since the ajax call was initiated, but we're still waiting
alert('The Ajax call has been made. We're moving on to the next call.');