JS/jQuery获取HTTPRequest请求标头?

Lwy*_*yrn 23 javascript ajax header request request-headers

在xhr对象中使用getAllResponseHeaders,可以在ajax调用之后获取所有响应头.但我找不到获取Request头字符串的方法,这可能吗?

Emi*_*l H 21

如果这是出于调试目的,那么您可以使用Firebug或Chrome开发者工具(以及IE中调用的任何功能)来检查从浏览器到服务器的网络流量.

另一种方法是使用类似这样的脚本:

$.ajax({
    url: 'someurl',
    headers:{'foo':'bar'},
    complete: function() {
        alert(this.headers.foo);
    }
});
Run Code Online (Sandbox Code Playgroud)

但是我认为只有已经定义的头文件headers可用(不确定如果标头被更改会发生什么(例如在beforeSend中).

你可以在http://api.jquery.com/jQuery.ajax/上阅读更多关于jQuery ajax的内容.

编辑:如果你想在XMLHttpRequest的所有调用setRequestHeader上捕获标题,那么你可以只使用该方法.这有点像黑客,当然你需要确保在任何请求发生之前运行包含下面代码的函数.

// Reasign the existing setRequestHeader function to 
// something else on the XMLHtttpRequest class
XMLHttpRequest.prototype.wrappedSetRequestHeader = 
  XMLHttpRequest.prototype.setRequestHeader; 

// Override the existing setRequestHeader function so that it stores the headers
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
    // Call the wrappedSetRequestHeader function first 
    // so we get exceptions if we are in an erronous state etc.
    this.wrappedSetRequestHeader(header, value);

    // Create a headers map if it does not exist
    if(!this.headers) {
        this.headers = {};
    }

    // Create a list for the header that if it does not exist
    if(!this.headers[header]) {
        this.headers[header] = [];
    }

    // Add the value to the header
    this.headers[header].push(value);
}
Run Code Online (Sandbox Code Playgroud)

现在,一旦在XMLHttpRequest实例上设置了标题,我们就可以通过检查xhr.headers例如将它们取出来

var xhr = new XMLHttpRequest();
xhr.open('get', 'demo.cgi');
xhr.setRequestHeader('foo','bar');
alert(xhr.headers['foo'][0]); // gives an alert with 'bar'
Run Code Online (Sandbox Code Playgroud)

  • 是的,似乎无法捕获请求标头 (2认同)