Javascript 从原型中添加自定义标题
我已原型化了Javascript 从原型中添加自定义标题,javascript,xmlhttprequest,request-headers,Javascript,Xmlhttprequest,Request Headers,我已原型化了XMLHttpRequest,以添加其他功能。 但是,当我尝试向调用添加自定义标题时,它不起作用(chrome developer工具栏中没有错误,也没有调用) 我的代码: (function(){ var originalOpenFunction = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function (method, url, async, user, pass) { //Add
XMLHttpRequest
,以添加其他功能。但是,当我尝试向调用添加自定义标题时,它不起作用(chrome developer工具栏中没有错误,也没有调用) 我的代码:
(function(){
var originalOpenFunction = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
//Add custom header
this.setRequestHeader('custom-header', 'value');
originalOpenFunction.call(this, method, url, async, user, pass);
};
})();
$.ajax("http://www.jsfiddle.net");
当我删除setRequestHeader
行时,我得到了预期的错误(不允许跨原点)
注意虽然我使用jquery测试javascript,但解决方案应该是原生javascript
通过以下方式暴露错误:
$.ajax("http://www.jsfiddle.net").fail(function (e) {
console.log(e);
});
您将获得:
InvalidStateError:未能对“XMLHttpRequest”执行“setRequestHeader”:必须打开对象的状态
这意味着您需要先调用open()
,然后再调用setRequestHeader()
然后您将遇到跨域问题。确保您没有试图对不受支持的域执行跨域请求。shell从http://fiddle.jshell.net
请求该域工作(返回HTML)
见: