【问题标题】:How to retrieve XHR response code (+timestamp) of AMD'ized Dojo?如何检索 AMD 化 Dojo 的 XHR 响应代码(+时间戳)?
【发布时间】:2012-08-28 07:36:53
【问题描述】:

对于“旧”Dojo,可以将第二个参数 ioargs 传递给 Xhr 请求 (see Example 6 here) 的 load 函数。这个ioargs 提供(除其他外)请求的时间戳和状态代码。

但是如何使用新的“更干净”(并且向前兼容)Dojo 来实现这一点?
不幸的是,我在current documentation 中找不到任何提示。

以下应该是上述引用示例到“新”Dojo 的移植。但是,ioargs 将是未定义的:

require( "dojo/request/xhr", "dojo/dom", "dojo/domReady!",
  function(request, dom){
    // Look up the node we'll stick the text under.
    var targetNode = dom.byId("getLicenseStatus");

    // The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
    request.get(
      "{{dataUrl}}dojo/LICENSE",
      {
        handleAs: "text",
        preventCache: true
      }
    ).then(
      function(data, ioargs){
        // FIXME: ioargs is undefined
        targetNode.innerHTML = "XHR returned HTTP status: " + ioargs.xhr.status;
      },
      function(error){
        targetNode.innerHTML = "An unexpected error occurred: " + error.response.status + ": " + error.response.text;
      }
    );
  }
);

我需要更改哪些内容才能使请求的时间戳和状态代码在加载函数中可用?

【问题讨论】:

  • request.get() 产生的 deferred 里面是否隐藏了信息?
  • request.get() 产生(正如@Kniganapolke 也指出)一个promise 对象。除了一些函数定义和原型构造函数之外,我找不到任何数据。

标签: javascript dojo xmlhttprequest


【解决方案1】:

request 返回一个特殊的promise (source):

从 dojo/request 调用返回的 Promise 有一个标准 Promise 上没有的附加属性:response.此属性是一个承诺,它将解析为更详细地描述响应的冻结对象(如果可用):

  • url - 用于发出请求的最终 URL(附加查询字符串)
  • options – 用于发出请求的选项对象
  • 文本 - 响应中数据的字符串表示
  • data – 响应中处理的数据(如果指定了 handleAs)
  • getHeader(headerName) – 从请求中获取标头的函数;如果提供者不提供标头信息,则此函数将返回 null。

因此,您应该将.then 链接到此promise.response 以访问所有上述属性:

var promise = request.get("{{dataUrl}}dojo/LICENSE");

promise.response.then(function(response) {
    console.log("status", response.status);
    console.log("url", response.url);
    console.log("data", response.data);
});

在 jsFiddle 上查看一个工作示例:http://jsfiddle.net/phusick/6wB2L/

【讨论】:

  • 谢谢。检索状态非常适合。虽然不可能得到请求的时间戳,对吧?
  • 似乎不是这样,但是您可以将timestamp: (new Date()).valueOf() 添加到请求选项中,然后您会在response.options.timestamp 中找到它(请参阅更新的jsFiddle)。或者考虑 request/registry 在每个请求中为您完成。
  • 这也帮助了我。谢谢。
  • 响应对象不仅具有上述属性(url,options,...),而且还有一个xhr属性,它引用了底层的XMLHttpRequest对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 2016-03-07
  • 2015-10-15
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多