如果这是出于调试目的,那么您可以只使用 Firebug 或 Chrome 开发人员工具(以及 IE 中调用的任何功能)来检查从浏览器到服务器的网络流量。
另一种方法是使用类似下面的脚本:
$.ajax({
url: 'someurl',
headers:{'foo':'bar'},
complete: function() {
alert(this.headers.foo);
}
});
但是我认为只有 headers 中已经定义的标头可用(不确定如果标头被更改(例如在 beforeSend 中)会发生什么。
您可以阅读更多关于 jQuery ajax 的信息:http://api.jquery.com/jQuery.ajax/
编辑: 如果您只想捕获 XMLHttpRequest 上对 setRequestHeader 的所有调用的标头,那么您可以包装该方法。这有点像 hack,当然您需要确保在任何请求发生之前运行下面的函数包装代码。
// 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'