我正在尝试进行连续的异步 ajax 调用,以便通过 jQuery 将用户的日程安排绘制到 HTML 表中。 每个响应都会返回一个 JSON 序列化数据集,其中包含两个表:一个是计划事件,另一个包含用户信息。
我遇到的问题是用户信息似乎与用户事件混淆了。也就是说,有时用户onfo不 针对不同的响应进行更改,以便将计划的事件绑定(bind)到不正确的用户。如果我将 AJAX 异步属性设置为 false,则一切正常。
重点是在数据返回时一一显示时间表,而不是让页面卡住直到所有数据返回。
有没有办法确保第一个 JAX 调用在后续调用执行之前完成?
(也许我对将 async 设置为 false 的理解不正确。这是否意味着在代码继续执行之前收集了所有数据?)
这是我当前的方法:
// When page loads
$(document).ready(function () {
// Get date range
debugger;
//GetStartDate(), GetEndDate() populates date range
//PopulateParams() does that for remaining parameters
$.when(GetStartDate(), GetEndDate())
.then(function () {
PopulateParams();
GetUserSchedule();
})
.fail(function () {
failureAlertMsg();
})
});
// Returns schedule for each person listed in between selected start and end dates
function GetUserSchedule() {
for (var i = 0; i < arrRequests.length; i++) {
$.when(
// Ajax call to web method, passing in string
$.ajax({
type: "POST",
url: URL/default.aspx/GetSchedules",
data: arrRequests[i], // example data: {"UserId":"6115","startDate":"\"7/1/2011\"","endDate":"\"7/31/2011\MoreVals: Vals} contentType: "application/json",
dataType: "json",
success: SuccessFunction,
error: function (d) { alert('Failed' + d.responseText + '\nPlease refresh page to try again or contact administrator'); }
})
)
.then(function () {
}
);
}
}
// On successful completion of call to web method, paint schedules into HTML table for each user
function SuccessFunction(data) {
if (data != null && data.d != null && data.d.Temp != null) {
// Calls a bunch of functions to paint schedule onto HTML table
// Data contains two tables: one contains user info and the other contains rows of info for each event for user
// at times, the user info is not the correct user or the events are not correct for user
}
最佳答案
在 $.ajax({..
写:
$.ajax({
async: false,
**rest of code**});
关于jquery - 有没有办法确保第一个 AJAX 调用在后续调用执行之前完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6899441/