【问题标题】:jQuery.when: Get the xhr status codejQuery.when: 获取 xhr 状态码
【发布时间】:2017-02-08 13:07:14
【问题描述】:

我有两个 ajax 调用,它们在使用 jQuery.when() 完成后执行一些回调

$.when(loadDataA(), loadDataB()).done(function(dataA, dataB) {
  console.log(xhr.status); // How do I get the xhr.status?
}

我想知道第一次通话的xhr.status。使用正常的 .done() 您可以执行以下操作:

.done(function(data, statusText, xhr) {
  console.log(xhr.status);
}

但我不能让它在我的情况下工作。

使用jQuery.when时如何获取?

【问题讨论】:

  • 如果您有多个 xhr 请求,您将需要多个统计信息
  • 我是这么认为的。你有如何做到这一点的例子吗?
  • 如果没有内置功能(没有找到),我会尝试让 loadDataA 和 B 返回一个包含 xhr 状态和数据的对象。然后,您可以从 dataA 和 dataB 中检索它。只是一个想法
  • dataA 是一个包含所有传递参数的数组。 dataA[2]XMLHttpRequest 对象 (fiddle)
  • @Andreas 你的就是答案。谢谢!

标签: jquery ajax .when


【解决方案1】:

来自$.when() 的文档:

如果 Deferred 在没有值的情况下被解析,则相应的 doneCallback 参数将是未定义的。如果 Deferred 解析为单个值,则相应的参数将保存该值。在 Deferred 解析为多个值的情况下,相应的参数将是这些值的数组。例如:

var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.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 );

在您的情况下,dataA 将是一个包含三个元素的数组:

dataA[0] -> data
dataA[1] -> statusText
dataA[2] -> xhr

有了这个……

使用jQuery.when时如何获取?

dataA[2].status

【讨论】:

    猜你喜欢
    • 2013-12-29
    • 2016-09-29
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多