简体   繁体   English

修改XMLHttpRequest中的请求标头

[英]Modiying request headers in an XMLHttpRequest

I've made an ajax call interceptor to listen for XMLHttpRequests. 我已经制作了一个ajax调用拦截器来监听XMLHttpRequests。

I would like to modify the request headers of the XHR. 我想修改XHR的请求标头。 For some reason I can only change them in XMLHttpRequest.send() . 出于某种原因,我只能在XMLHttpRequest.send()更改它们。 Is it to early to modify them in XMLHttpRequest.open() ? 是否要在XMLHttpRequest.open()修改它们? It throws the exception that I pasted in the code below. 它抛出了我粘贴在下面的代码中的异常。

So, why do I get an error? 那么,为什么我会收到错误?

(function (open) {

    XMLHttpRequest.prototype.open = function () {

        this.setRequestHeader('foo', 'bar'); 
        // InvalidStateError: An attempt was made to 
        // use an object that is not, or is no longer, usable

        open.apply(this, arguments);
    };

})(XMLHttpRequest.prototype.open);

(function (send) {

    XMLHttpRequest.prototype.send = function () {

        this.setRequestHeader('foo', 'bar'); // OK

        send.apply(this, arguments);
    };

})(XMLHttpRequest.prototype.send);

for(var i = 0; i < 3; i++){

    var rnd = Math.round(Math.random()*3+1),
        httpRequest = new XMLHttpRequest();

    httpRequest.onreadystatechange = function () { };
    httpRequest.open('GET', '/echo/json?delay=' + rnd);
    httpRequest.send();

}

http://jsfiddle.net/zrZ3a/2/ http://jsfiddle.net/zrZ3a/2/

What if you swap: 如果你交换怎么办:

this.setRequestHeader('foo', 'bar'); 
open.apply(this, arguments);

to get: 要得到:

open.apply(this, arguments);
this.setRequestHeader('foo', 'bar'); 

does it work then? 它有效吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM