h5获取http请求头_javascript – JS/jQuery获取HTTPRequest请求头?

本文介绍了如何通过JavaScript和jQuery获取HTTP请求头。您可以使用浏览器的开发者工具进行调试,或者使用jQuery的ajax方法并在complete回调中访问请求头。另外,提供了一种覆盖XMLHttpRequest的setRequestHeader方法以记录所有设置的头部的方法。
摘要由CSDN通过智能技术生成

如果这是为了调试目的,那么您只需使用Firebug或Chrome Developer Tools(以及IE中的所有功能)来检查从浏览器到服务器的网络流量。

一个替代方案是使用像这样的脚本:

$.ajax({

url: 'someurl',

headers:{'foo':'bar'},

complete: function() {

alert(this.headers.foo);

}

});

但是,我认为只有标头中已经定义的头可用(不知道如果标题被更改(例如在BeforeSend中)会发生什么。

编辑:如果你想在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);

}

现在,一旦在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'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值