4
我已經做了一個Ajax調用攔截器來偵聽XMLHttpRequests。在XMLHttpRequest中修改請求標頭
我想修改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();
}
是的,你能解釋爲什麼嗎? – Johan
因爲在設置它之前需要將其打開。 – epascarello