【问题标题】:Ajax $.when returns different object when multiple parameters are usedAjax $.when 使用多个参数时返回不同的对象
【发布时间】:2015-03-27 14:39:34
【问题描述】:

我正在使用 jquery $.when 来调用返回 json 的 REST url。

当我使用单个参数执行 $.when 时,我在 data1 结果中得到的对象与执行多个结果时不同,即使返回参数都应该是独立的。

<script>
$(document).ready(function () {

    fun1(1025);
    fun2(1025);

    function fun1(id) {
        $.when(_restFun1(id), _restFun1(id)).done(function(data1, data2) {
            console.log(data1);
        });
    }

    function fun2(id) {
        $.when(_restFun1(id)).done(function(data1) {
            console.log(data1);
        });
    }

});
</script>

打印到 console.log 的对象是不同的,即使这两个函数应该打印同一个对象!

注意

_restFun1 函数是这样的:

function _restFun1(id)
{
    return $.ajax({
        url: "http://192.123.12.3/test.php?id="+id,
        data: "",
        dataType: 'json',
        success: function (data1) {
        }
    });
}

它返回一个json对象,在一种情况下,我得到json对象,在多次调用的情况下,我得到一个具有多个其他字段的对象,如responseText,responseJSON,一个“成功”字符串,然后在一个数组中我需要的真正的 JSON。

【问题讨论】:

  • 你期望什么输出,你得到什么输出?查看_restFun() 函数,以及被调用的服务器端代码也可能有所帮助。
  • 请将日志输出复制/粘贴到问题中。

标签: jquery ajax .when


【解决方案1】:

注意,在 jQuery.when() documentation 上,关于返回的 jQuery.ajax 调用返回数组 [responseText, textStatus, jqxhr] ("success") 或 [jqxhr, textStatus, errorThrown] ("error") 并不完全清楚

如果 Deferred 解析为单个值,则对应的参数 将保持该值。在延迟解决的情况下 多个值,对应的参数将是这些值的数组 价值观。

最接近的示例演示可以在文档中找到

var d1 = new $.Deferred();
var d2 = new $.Deferred();
var d3 = new $.Deferred();

$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
    console.log( v1 ); // v1 is undefined
    console.log( v2 ); // v2 is "abc"
    console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
});

d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 ); // returned as `array` at `.done()`

另见

Ajax response has different format when used with JQuery when function

jquery when documentation for response and errors


响应将是array [responseText, textStatus, jqxhr],其中responseText 来自服务器的响应; textStatussuccesserrorjqxhrjQuery jqXHR 对象

试试

function fun1(id) {
  $.when(_restFun1(id), _restFun1(id))
  .done(function(data1, data2)) {
    // `data[0]`, `data1[0]` should be `responseText` , `responseJSON`    
     console.log(data1[0], data2[0]);  
  })
}

【讨论】:

猜你喜欢
  • 2018-08-26
  • 2019-05-05
  • 1970-01-01
  • 2017-11-29
  • 2019-02-22
  • 2020-10-28
  • 2021-08-29
  • 2013-12-29
  • 1970-01-01
相关资源
最近更新 更多