4

我制作了一个 ajax 调用拦截器来监听 XMLHttpRequests。

我想修改 XHR 的请求标头。出于某种原因,我只能将它们更改为XMLHttpRequest.send(). 修改它们是否为时过早XMLHttpRequest.open()?它抛出了我在下面的代码中粘贴的异常。

那么,为什么我会收到错误消息?

(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/

4

1 回答 1

12

如果你交换:

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

要得到:

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

那么它有效吗?

于 2013-06-11T19:28:11.953 回答