使用“旧”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/