【问题标题】:how to use .then function with parameters in jquery如何在jquery中使用带有参数的.then函数
【发布时间】:2011-02-02 05:01:22
【问题描述】:
//******************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

【问题讨论】:

  • 你不能把这个问题合并到你以前的问题吗?我的意思是它们只是相关的,不是吗?
  • 是的,但我不想让读者感到困惑。因为他们想更快地得到想法

标签: jquery ajax


【解决方案1】:
$.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);
}

【讨论】:

  • 注意jqXHR对象是刚刚在jquery1.5中添加的,否则很好回答
  • @macarthy - 是的,而且 OP 肯定是 1.5,否则他不能使用$.when() ;)
猜你喜欢
  • 2017-03-25
  • 2013-10-27
  • 2014-05-22
  • 2016-11-13
  • 2014-08-28
  • 1970-01-01
  • 2019-04-27
  • 2011-09-27
  • 2014-09-03
相关资源
最近更新 更多