我正在使用以下代码记录 xhr 请求:
(function(open) {
XMLHttpRequest.prototype.open = function(method, url, async) {
if (..something..)
{
...
open.call(this, method, url, async);
...
}
};
})(XMLHttpRequest.prototype.open);
所以现在我想获取响应 header ,例如 console.log(getAllResponseHeaders())
我尝试在代码中的任何地方实现它,但我没有得到任何结果,这意味着没有记录任何内容。在哪里或如何获取响应 header ?
最佳答案
请记住, header 仅在到达后才存在,而不是之前。这意味着您必须使用事件监听器来捕获它们。根据状态4
,它们肯定存在。
(function(open, headers) {
var headhandle = function () {
if (this.readyState === 4) console.log(headers.call(this));
};
XMLHttpRequest.prototype.open = function(method, url, async) {
this.addEventListener('readystatechange', headhandle);
open.call(this, method, url, async);
};
}(XMLHttpRequest.prototype.open, XMLHttpRequest.prototype.getAllResponseHeaders));
var x = new XMLHttpRequest();
x.open();
x.send();
/*
Date: Tue, 31 Dec 2013 13:43:42 GMT
Content-Encoding: gzip
Vary: *
Last-Modified: Tue, 31 Dec 2013 13:43:43 GMT
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
Cache-Control: public, max-age=60
Content-Length: 14317
Expires: Tue, 31 Dec 2013 13:44:43 GMT
*/
使用 readyState === 3
进行测试,但没有给出结果,因此您肯定需要等待 4
。
关于javascript - 如何在 xhr 对象上设置 getAllResponseHeaders(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20858206/