javascript - 如何检索 AMD'ized Dojo 的 XHR 响应代码(+时间戳)?

标签 javascript dojo xmlhttprequest

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

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

以下应该是上面引用的示例到"new"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 返回一个特殊的promise ( source ):

Promises returned from dojo/request calls have an additional property not available on standard promises: response. This property is a promise that will resolve to a frozen object (where available) describing the response in more detail:

  • url – final URL used to make the request (with query string appended)
  • options – options object used to make the request
  • text – string representation of the data in the response
  • data – the handled data in the response (if handleAs was specified)
  • getHeader(headerName) – a function to get a header from the request; if a provider doesn’t provide header information, this function will return 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/

关于javascript - 如何检索 AMD'ized Dojo 的 XHR 响应代码(+时间戳)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12154748/

相关文章:

javascript - 不播放视频的 HTML5 视频时长

javascript - 使用 selenium 和 python 在文本框中快速写入

javascript - 如何在不失去调用 ng-click 的能力的情况下禁用输入?

javascript - 在发送 JavaScript 之前拦截 XHR 并更改请求 header 和 url

eclipse - rest 服务在 Eclipse 中部署时有效,但在 Tomcat 中无效

javascript - 为什么这段js会抛出DOM异常呢?

javascript - Polymer:更改必填字段空消息

ruby-on-rails - Dojo + Rails 3.2.8 + CoffeeScript

javascript - Dijit 选择,组合框中的项目已禁用 = true 不起作用

javascript - 为什么多个以编程方式生成的 FilteringSelect 不能共享一个存储?