2011-06-10 71 views
3

我正在使用PHP。我想完成jQuery AJAX過程,(完成過程並在數據返回主頁面後返回)。如何做一些jQuery後的其他jquery的事情ajax

然後做下一個jQuery的事情。任何想法如何做到這一點?

$.ajax({ 
    url: "page1.php", 
    dataType: "html", 
    type: 'POST', 
    data: "value=" + value, 
    success: function(data){ 
    //some process 
    } 
});//ajax1 
$.ajax({ 
    url: "page2.php", 
    dataType: "html", 
    type: 'POST', 
    data: "value=" + value, 
    success: function(data){ 
    //some process 
    } 
});//ajax2 
$.ajax({ 
    url: "page3.php", 
    dataType: "html", 
    type: 'POST', 
    data: "value=" + value, 
    success: function(data){ 
    //some process 
    } 
});//ajax3 

// finish all the 3 ajax process, do the below code 
$(".page").css('display','block'); 

回答

12

如果您使用jQuery 1.5或更好,你可以用天上$.when結構,它使用$.Deferred概念在該版本的jQuery的首次實施。當幾個AJAX請求都完成時,您可以運行一個函數(或多個函數)。

所以,你的代碼應該是這樣的:

$.when($.ajax({ 
    url: "page1.php", 
    dataType: "html", 
    type: 'POST', 
    data: "value=" + value, 
    success: function (data) { 
     //some process 
    } 
}), $.ajax({ 
    url: "page2.php", 
    dataType: "html", 
    type: 'POST', 
    data: "value=" + value, 
    success: function (data) { 
     //some process 
    } 
}), $.ajax({ 
    url: "page3.php", 
    dataType: "html", 
    type: 'POST', 
    data: "value=" + value, 
    success: function (data) { 
     //some process 
    } 
})).then(function() { 

}); 
+0

謝謝你分享! $ .when()似乎是非常方便的! – 2011-06-10 22:58:00

+0

+1當!從來沒有聽說過它,我相信我會用這個:) – 2011-06-10 23:00:39

+0

+1一個美妙的答案,謝謝。 – cj333 2011-06-10 23:02:18

2

如果你有Ajax操作的任意號碼,你可以做這樣的事情:

var arr = []; 
arr.push($.ajax(...)); 
arr.push($.ajax(...)); 
/* put as many ajax operations as you want into arr */ 
$.when.apply(arr).then(function() { /* on success */ }, 
         function() { /* on error */ }); 

這是我最喜歡的技術同步多個ajax調用。

1

只是爲了記錄在案,以便預jQuery的1.5答案就在這裏,太:

$.ajax({ 
    url: "page1.php", 
    dataType: "html", 
    type: 'POST', 
    data: "value=" + value, 
    success: function(data){ 
    $.ajax({ 
     url: "page2.php", 
     dataType: "html", 
     type: 'POST', 
     data: "value=" + value, 
     success: function(data){ 
     $.ajax({ 
      url: "page3.php", 
      dataType: "html", 
      type: 'POST', 
      data: "value=" + value, 
      success: function(data){ 
      // finish all the 3 ajax process, do the below code 
      $(".page").css('display','block'); 
      } 
     });//ajax3 
     } 
    });//ajax2 
    } 
});//ajax1 

我們希望,如果不出意外這說明做事的新的jQuery 1.5方式的價值:-)

相關問題