問題描述
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) {
this.addEventListener("readystatechange", function(event) {
if(this.readyState == 4){
var self = this;
var response = {
method: method,
uri: uri,
responseText: self.responseText
};
console.log(response);
} else {
console.log(this.readyState);
}
}, false);
open.call(this, method, uri, async, user, pass);
};
我正在嘗試在發送 XHR 之前收聽它們.$.ajax
方法中類似于 jQuery 的 beforeSend 方法.
I am trying to listen for XHR before they are being sent. Something similar to jQuery's beforeSend in the $.ajax
method.
我的目標是在發送所有 XHR 之前監聽它們.我想最接近的方法是檢查上面是否 this.readyState === 1
?
My goal is to listen for all XHR's before they are being sent. I suppose the closest thing would be to check above if this.readyState === 1
?
上面的代碼是否會因為我在 XMLHttpRequest
上使用原型而導致任何 ajax 庫(如 jQuery)出現故障?
Would the code above cause any ajax libraries like jQuery to malfunction because I use prototype on XMLHttpRequest
?
推薦答案
我正在嘗試在發送 XHR 之前監聽它們.
I am trying to listen for XHR before they are being sent.
然后嘗試欺騙 send()
方法,而不是 open()
方法.
Then try to spoof the send()
method, not the open()
one.
上面的代碼是否會因為我在 XMLHttpRequest 上使用原型而導致任何 ajax 庫(如 jQuery)出現故障?
Would the code above cause any ajax libraries like jQuery to malfunction because I use prototype on XMLHttpRequest?
不,不是真的.只是,
- 在那些庫選擇不使用
XMLHttpRequest
(尤其是 IE)的情況下它不起作用 - …如果瀏覽器不支持
XMLHttpRequest
對象(或不支持訪問或修改其原型),甚至會失敗 - libs 可能能夠通過在你可以之前取消引用函數來解決你的欺騙問題(盡管我不知道有什么常見的 lib)
- 您的代碼使用固定數量的參數調用本機方法,不確定這是否會影響任何內容,并且它不會重新返回結果(即使我們知道它是
undefined
).為 100% 確定,請使用return open.apply(this, arguments);
.
- it won't work where those libs choose not to use
XMLHttpRequest
(particularly IE) - …and even fail if the browser does not support the
XMLHttpRequest
object (or does not support accessing or modifying its prototype) - libs might be able to work around your spoof by dereferencing the functions before you can (though I don't know any common lib that does)
- Your code calls the native method with a fixed number of arguments, not sure if that affects anything, and it does not re-return the result (even if we know it's
undefined
). To be 100% sure, usereturn open.apply(this, arguments);
.
這篇關于自定義 XMLHttpRequest.prototype.open的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!