我正在執行多個(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