[英]How to access the headers a HTTP response that you didn't send by AJAX using javascript?
[英]How do you access http headers when making ajax requests with Promises?
我正在使用bluebird.js解決jquery ajax請求,並且出人意料地難以訪問我的請求的http標頭。
樣例代碼:
Promise.resolve($.get(...)).then(function(data){
//wtb http headers
});
我試圖訪問響應中返回的http標頭。 僅針對ajax請求執行此操作很簡單,我認為有一個比我聰明的人已經實現了此承諾。
解決此問題的一種方法是僅保留對jqXHR對象的引用,以便以后可以訪問它:
var jqXHR = $.get(...);
Promise.resolve( jqXHR ).then( function ( data ) {
var headers = jqXHR.getAllResponseHeaders();
} );
jQuery Promise和Bluebird Promise(兼容Promises / A + )之間的區別是,您的then
函數僅獲取一個參數。 如果要保留jQuery提供的所有信息,則必須將其包裝在一個對象中:
Promise.resolve($.get(...).then(function(data, status, xhr) {
return {
data: data,
status: status,
xhr: xhr
};
})).then(function (data) {
// data.data has the response data
// data.xhr contains the jqXHR object
});
當通過使用jQuery將jqXHR作為正式變量提供給成功和錯誤處理程序時,為什么將jqXHR
強制為其他Promise?
$.get(...).then(function(data, testStatus, jqXHR) {
var headers = jqXHR.getAllResponseHeaders();
...
}, function(jqXHR, testStatus, errorThrown) {
var headers = jqXHR.getAllResponseHeaders();
...
});
如果出於任何原因仍然需要強制jqXHR,則將整個表達式包裝在Promise.resolve(...)
。 .then .then()
返回的jQuery承諾與jqXHR一樣具有強制性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.