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

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

问题描述

在使用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);
    }
});

不过,我想只有在标题已经定义的标题是可用的(不知道,如果头被改变(例如在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的阿贾克斯: http://api.jquery.com/jQuery.ajax/

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

编辑:如果您想只捉对所有呼叫的标头setRequestHeader的XMLHtt prequest那么你可以wrapp该方法。这是一个黑客位的,当然你需要确保功能包装code以下运行前的任何请求的发生。

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

现在,一旦头已经被设置在一个 XMLHtt prequest 例如,我们可以让他们通过检查 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的获取HTT prequest请求头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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