jquery - 如何在jquery中使用带有参数的.then函数

标签 jquery ajax

//******************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

最佳答案

$.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);
}

关于jquery - 如何在jquery中使用带有参数的.then函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4870945/

相关文章:

javascript - 如何在javascript中获取td内部列表的值

javascript - 为什么 jQuery 对我的所有列表元素应用点击阻止

javascript - 如何在循环中获取标签的文本及其类名?

jquery - facebook 页面插件在 ajax 页面加载后不起作用

Javascript 何时显示结果

javascript - 无法在 IE 8 及以下版本中使用 jQuery 解析文件,因为它不是 XML(即使它有点像 XML)

javascript - jquery 无法从隐藏字段中获取值

javascript - 记录jQuery中调用的方法和参数

javascript - 在不触发滚动条的情况下使用 css 和 jquery 将 div 滑出?

ajax - PUTting 到 S3 时出现 ERR_CONNECTION_RESET