如何检索AMD化Dojo的XHR响应代码(+时间戳)?

Tor*_*örn 8 javascript dojo xmlhttprequest

使用"旧"Dojo,可以将第二个参数传递给Xhr请求ioargsload函数(参见此处的示例6).这ioargs提供了(除其他外)请求的时间戳和状态代码.

但是,如何通过新的"更清洁"(和向前兼容)Dojo实现这一目标?
不幸的是,我在当前的文档中找不到任何提示.

以下应该是上面引用的"新"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;
      }
    );
  }
);
Run Code Online (Sandbox Code Playgroud)

我需要更改什么才能在加载功能中使用请求的时间戳和状态代码?

phu*_*ick 13

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

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

  • url - 用于发出请求的最终URL(附加查询字符串)
  • options - 用于发出请求的选项对象
  • text - 响应中数据的字符串表示形式
  • 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);
});
Run Code Online (Sandbox Code Playgroud)

请参阅jsFiddle的一个工作示例:http://jsfiddle.net/phusick/6wB2L/