3

私はPHPを使用しています。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');
4

3 に答える 3

12

jQuery 1.5 以降を使用している場合は、そのバージョンの jQuery で最初に実装された概念を使用する、天国のような$.when構造を使用できます。$.Deferredいくつかの 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 () {

});
于 2011-06-10T22:55:07.860 に答える
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 呼び出しを同期するための私のお気に入りの手法です。

于 2011-06-11T00:51:11.260 に答える
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 のやり方の価値を示しています :-)

于 2011-06-11T01:39:11.313 に答える