問(wèn)題描述
使用舊"Dojo,可以將第二個(gè)參數(shù) ioargs
傳遞給 Xhr 請(qǐng)求的 load
函數(shù)(請(qǐng)參見(jiàn)此處的示例 6).此 ioargs
提供(除其他外)請(qǐng)求的時(shí)間戳和狀態(tài)代碼.
With the "old" Dojo one could pass a second argument ioargs
to the load
function of a Xhr request (see Example 6 here). This ioargs
provided (among other things) the timestamp and status code of the request.
但是如何使用新的更干凈"(并且向前兼容)Dojo 來(lái)實(shí)現(xiàn)這一點(diǎn)?
不幸的是,我在 當(dāng)前文檔中找不到任何提示一個(gè)>.
But how can I achieve this with the new and "cleaner" (and forward compatible) Dojo?
Unfortunately, I could not find any hints in the current documentation.
以下應(yīng)該是上述引用示例到新"Dojo 的移植.但是,ioargs
將是未定義的:
The following should be a port of above referenced example to the "new" Dojo. But, ioargs
will be undefined:
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;
}
);
}
);
我需要更改哪些內(nèi)容才能使請(qǐng)求的時(shí)間戳和狀態(tài)代碼在加載函數(shù)中可用?
What do I need to change to have the request's timestamp and status code available in the load function?
推薦答案
request
返回一個(gè)特殊的 promise
(來(lái)源):
request
returns a special promise
(source):
從 dojo/request 調(diào)用返回的 Promise 有一個(gè)標(biāo)準(zhǔn) Promise 上沒(méi)有的附加屬性:response.此屬性是一個(gè)承諾,它將解析為更詳細(xì)地描述響應(yīng)的凍結(jié)對(duì)象(如果可用):
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 - 用于發(fā)出請(qǐng)求的最終 URL(附加查詢字符串)
- options – 用于發(fā)出請(qǐng)求的選項(xiàng)對(duì)象
- 文本 - 響應(yīng)中數(shù)據(jù)的字符串表示
- data – 響應(yīng)中處理的數(shù)據(jù)(如果指定了 handleAs)
- getHeader(headerName) – 從請(qǐng)求中獲取標(biāo)頭的函數(shù);如果提供者不提供標(biāo)頭信息,則此函數(shù)將返回 null.
因此,您應(yīng)該將 .then
鏈接到此 promise.response
以訪問(wèn)所有上述屬性:
So you should chain .then
to this promise.response
to get access to all the aforementioned properties:
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 上查看一個(gè)工作示例:http://jsfiddle.net/phusick/6wB2L/
See a working example at jsFiddle: http://jsfiddle.net/phusick/6wB2L/
這篇關(guān)于如何檢索 AMD 化 Dojo 的 XHR 響應(yīng)代碼(+時(shí)間戳)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!