JS/jQuery 获取 HTTPRequest 请求标头? [英] JS/jQuery get HTTPRequest request headers?

查看:130
本文介绍了JS/jQuery 获取 HTTPRequest 请求标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using getAllResponseHeaders in the xhr object, is possible to get all the response headers after an ajax call. But I can't found a way to get the Request headers string, is that possible ?

推荐答案

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

If this is for debugging purposes then you can just use Firebug or Chrome Developer Tools (and whatever the feature is called in IE) to examine the network traffic from your browser to the server.

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

An alternative would be to use something like this script:

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

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

However I think only the headers already defined in headers is available (not sure what happens if the headers are altered (for instance in beforeSend).

您可以在以下位置阅读更多关于 jQuery ajax 的信息:http://api.jquery.com/jQuery.ajax/

You could read a bit more about jQuery ajax at: http://api.jquery.com/jQuery.ajax/

如果您只想捕获对 XMLHttpRequest 上的 setRequestHeader 的所有调用的标头,那么您可以包装该方法.这有点麻烦,当然您需要确保在任何请求发生之前运行包装下面的代码的函数.

If you want to just catch the headers on all calls to setRequestHeader on the XMLHttpRequest then you can just wrapp that method. It's a bit of a hack and of course you would need to ensure that the functions wrapping code below is run before any of the requests take place.

// 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);
}

现在,一旦在 XMLHttpRequest 实例上设置了标头,我们就可以通过检查 xhr.headers 例如

Now, once the headers have been set on an XMLHttpRequest instance we can get them out by examining xhr.headers e.g.

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

这篇关于JS/jQuery 获取 HTTPRequest 请求标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆