2011-02-02 15 views
1
//******************Example for multiple ajax success and failure*************// 
    function doAjax1(){ 
     var data="ajax_mode=request1&sample_data1=sample_data1"; 
     return $.get("ajax.php",data,function(msg){ 
      //alert(msg); 
     }); 
    } 

    function doAjax2(){ 
     var data="ajax_mode=request2"; 
     return $.get("ajax.php",data,function(msg){ 
      //alert(msg); 
     }); 
    } 

//success and error cant be used with $.when() 
    $.when(doAjax1(), doAjax2()).then(function(msg){ 
     alert('alert oncompletion of both ajax'+msg); //Not returns both ajax result 
     console.log('I fire once BOTH ajax requests have completed!'); 
    }).fail(function(){ 
     console.log('I fire if one or more requests failed.'); 
    }).done(function(){ 
     console.log('I fire if one or more requests done.'); 
    }); 
//****************************************************************************// 

PHPコード jqueryの中のパラメータを持つ関数を.then使用方法

<?php if(isset($_REQUEST['ajax_mode'])) { $ajax_mode=trim($_REQUEST['ajax_mode']); switch($ajax_mode){ case 'request1': $sample_data1=$_REQUEST['sample_data1']; $checking="checking ajax req 1"; echo $sample_data1; break; case 'request2': $checking="checking ajax req 2"; echo $checking; break; } } ?> 

ajax.php質問:
機能doAjax1、doAjax2がサーバーから値を返します。 複数のajaxリクエストに $.when()を使用します

すべてのAjaxリクエストが完了したら、すべてのajax戻り値を取得する必要があります。

私はあなたは自分にこの質問をマージすることができませんでしたsample_data1, sample_data2

+0

私の期待のアラート結果

を[それがこのように警告し、なぜ私を説明してください]警告sample_data1,success,[object Object]$.when().then(function(msg){alert(msg)})

の検索結果を使用していました前?彼らはちょうど関連しているという意味ですか? – Reigel

+0

ええ、その関連が、私は読者を混乱させたくありません。彼らはもっと素早くアイデアを得たいからです。 –

答えて

6
$.when(doAjax1(), doAjax2()) 
    .then(myFunc, myFailure); 
// Execute the function myFunc when both ajax requests are successful, 
// or myFailure if either one has an error. 

myFunc = function(a1, a2){ 
    /* a1 and a2 are arguments resolved for the 
     doAjax1 and doAjax2 ajax requests, respectively */ 
    var jqXHR1 = a1[2]; /* arguments are [ "success", statusText, jqXHR ], this explains why you got `sample_data1,success,[object Object]` in your alert */ 
    alert(jqXHR1.responseText); 
} 
+0

jqXHRオブジェクトがjquery1.5に追加されたことに注意してください。そうでなければ良い答え – macarthy

+1

@macarthy - はい、OPは間違いなく1.5です。そうでなければ '$ .when()' ;) – Reigel

+0

良い点、完全な答え! :-) – macarthy

関連する問題