如何检索AMD的XHR响应代码(+时间戳)'大型Dojo

How to retrieve XHR response code (+timestamp) of AMD'ized Dojo?

本文关键字:时间戳 Dojo 大型 代码 XHR 何检索 检索 AMD 响应      更新时间:2023-09-26

使用"旧"Dojo,可以将第二个参数ioargs传递给Xhr请求的load函数(请参见此处的示例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;
      }
    );
  }
);

我需要更改什么才能在加载函数中获得请求的时间戳和状态代码?

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

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

  • url–用于发出请求的最终url(附带查询字符串)
  • options–用于发出请求的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);
});

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