【发布时间】:2012-03-03 08:41:57
【问题描述】:
我在移动应用中,我使用多个 Ajax 调用从 Web 服务器接收数据,如下所示
function get_json() {
$(document).ready(function() {
$.ajax({
url: 'http://www.xxxxxxxxxxxxx',
data: {
name: 'xxxxxx'
},
dataType: 'jsonp',
//jsonp: 'callback',
//jsonpCallback: 'jsonpCallback',
success: function(data) {
$.each(data.posts, function(i, post) {
$.mobile.notesdb.transaction(function(t) {
t.executeSql('INSERT into bill (barcode, buildingcode, buildingaddress, flatname, flatdescription, entryseason, period, amount, pastpayments, todaypayments, paydate, receiptno) VALUES (?,?,?,?,?,?,?,?,?,?,?,?);', [post.Id, post.Code, post.Address, post.Name, post.Description, post.EntrySeason, post.Period, post.Revenue, post.PastPayments, post.todaypayments, post.paydate, post.receiptno],
//$.mobile.changePage('#page3', 'slide', false, true),
null);
});
$('#mycontent').append(post.Name);
});
}
});
$.ajax({
xxxx
});
$.ajax({
xxxx
});
});
}
如何强制第二个 ajax 调用在第一个结束后开始……第三个在第二个结束后开始,依此类推?
【问题讨论】:
-
唯一的问题是一个失败的 AJAX 调用将导致没有其他 AJAX 调用被进行(因为没有“如果 AJAX 调用失败则执行此操作”,它只会等待一个“成功”永远)。也许这正是您想要的……只是需要考虑的事情。
-
我认为你最好按照@Lyon 的建议使用 $.when。