как использовать функцию .then с параметрами в jquery - PullRequest
1 голос
/ 02 февраля 2011
//******************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 ajax.php

<?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;

    }
}
?>

Вопрос: Функция doAjax1, doAjax2 возвращает значение с сервера. Я собираюсь использовать $.when() для нескольких запросов AJAX

Мне нужно получить все возвращаемые значения Ajax после выполнения всех запросов AJAX.

я использовал $.when().then(function(msg){alert(msg)})

Результат оповещения sample_data1,success,[object Object] [Пожалуйста, объясните мне, почему он так предупреждает]

Мой ожидаемый результат оповещения sample_data1, sample_data2

1 Ответ

6 голосов
/ 02 февраля 2011
$.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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...