我正在执行多个(3)ajax请求。我怎样才能检查他们是否都成功返回,并且只有在这之后再对输出做些什么。我想过要链接请求,但这样请求不会同时执行。如何检查多个Ajax请求的完成?
最终我试图加载三个表格,并在加载后为他们的位置设置动画。只有在加载完所有表后,动画才会发生。
此外,处理多个ajax调用有什么好的做法?目前,语法只是重复前面的内容时看起来并不“美观”。
谢谢!
这里是我的代码:
// THIS TABLE
$.ajax({
type: 'POST',
url: 'includes/content/bookingsystem/b_dayview.php',
data: $(this).attr('name') + '=true',
success: function(output) {
$('#bookingTableThis').animate({
left: direction + '=820'
}, 500, function() {
$('#bookingTableThis').html(output);
});
}
});
// PREV TABLE
$.ajax({
type: 'POST',
url: 'includes/content/bookingsystem/b_dayview.php',
data: $(this).attr('name') + '=true&dateShift=prev',
success: function(output) {
$('#bookingTablePrev').animate({
left: direction + '=820'
}, 500, function() {
$('#bookingTablePrev').html(output);
});
}
});
// NEXT TABLE
$.ajax({
type: 'POST',
url: 'includes/content/bookingsystem/b_dayview.php',
data: $(this).attr('name') + '=true&dateShift=next',
success: function(output) {
$('#bookingTableNext').animate({
left: direction + '=820'
}, 500, function() {
$('#bookingTableNext').html(output);
});
}
});
Genesis的答案是当场就可惜它产生的另一个问题。很多时候,我在Javascript中传递变量时遇到了问题 - 在这种情况下也是如此。每个AJAX调用的输出不喜欢显示的“则”函数内:
var outputThis;
var outputPrev;
var outputNext;
$.when(function(){
// THIS TABLE
$.ajax({
type: 'POST',
url: 'includes/content/bookingsystem/b_dayview.php',
data: $(this).attr('name') + '=true',
success: function(output) { outputThis = output; }
});
// PREV TABLE
$.ajax({
type: 'POST',
url: 'includes/content/bookingsystem/b_dayview.php',
data: $(this).attr('name') + '=true&dateShift=prev',
success: function(output) { outputPrev = output; }
});
// NEXT TABLE
$.ajax({
type: 'POST',
url: 'includes/content/bookingsystem/b_dayview.php',
data: $(this).attr('name') + '=true&dateShift=next',
success: function(output) { outputNext = output; }
});
}).then(function(){
// THIS
$('#bookingTableThis').animate({
left: direction + '=820'
}, 500, function() {
$('#bookingTableThis').html(outputThis);
});
// PREV
$('#bookingTablePrev').animate({
left: direction + '=820'
}, 500, function() {
$('#bookingTablePrev').html(outputPrev);
});
// NEXT
$('#bookingTableNext').animate({
left: direction + '=820'
}, 500, function() {
$('#bookingTableNext').html(outputNext);
});
});
哇,从来没有听说过jQuery中的“当”的功能,超级有用。好的提示! –
这肯定是我要求的。哇,简单的jQuery仍令我惊叹。现在我遇到了另一个问题,但是当时有关。如何将输出变量传递给“when”函数。我试着在when-then部分之外首先设置变量,并在每个ajax函数内部定义它们,最后在“when”函数中读取它们 - 但是很明显,在范围界定方面存在问题。总之,非常感谢! – Dusty