h5获取http请求头,JS / jQuery的获取HTT prequest请求头?

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 ?

解决方案

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

}

});

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).

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

EDIT: 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);

}

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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值