I've made an ajax call interceptor to listen for XMLHttpRequests.
我已经制作了一个ajax调用拦截器来监听XMLHttpRequests。
I would like to modify the request headers of the XHR. For some reason I can only change them in XMLHttpRequest.send()
. Is it to early to modify them in XMLHttpRequest.open()
? It throws the exception that I pasted in the code below.
我想修改XHR的请求标头。出于某种原因,我只能在XMLHttpRequest.send()中更改它们。是否要在XMLHttpRequest.open()中修改它们?它抛出了我粘贴在下面的代码中的异常。
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/
1 个解决方案
#1
12
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?
它有效吗?
#1
12
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?
它有效吗?