2012-03-14 104 views
8

我試圖通過覆蓋XMLHttpRequest的發送函數將XMLHttpRequest發送到服務器的數據記錄(並稍後修改)。我的函數將數據正確地記錄到控制檯,但請求沒有完成,所以瀏覽器一直等待響應。任何想法有什麼問題的代碼?覆蓋XMLHttpRequest的發送方法

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send; 
var newSend = function(vData) { console.log("data: " + vData); realSend(vData); }; 
XMLHttpRequest.prototype.send = newSend;
+0

可能的重複http://stackoverflow.com/questions/4410218/trying-to-keep-track-of-number-of-outstanding-ajax-requests-in-firefox – 2012-03-14 11:22:54

回答

16
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send; 
// here "this" points to the XMLHttpRequest Object. 
var newSend = function(vData) { console.log("data: " + vData); this.realSend(vData); }; 
XMLHttpRequest.prototype.send = newSend; 
+0

謝謝,那確實很簡單。 – user1268760 2012-03-14 11:57:23

18

你已忘了this

this.realSend(vData); 

但是,你並不需要一個新的方法添加到原型:

var send = XMLHttpRequest.prototype.send; 

XMLHttpRequest.prototype.send = function(data) { 
    send.call(this, data); 
} 

使用封,你也可避免流氓變量:

!function(send){ 
    XMLHttpRequest.prototype.send = function (data) { 
     send.call(this, data); 
    } 
}(XMLHttpRequest.prototype.send); 
+1

謝謝關閉建議,代碼看起來似乎更加清潔。 – user1268760 2012-03-14 11:59:42

+3

[感嘆號在函數之前做了什麼?](http://stackoverflow.com/q/3755606/238421) – 2014-02-21 11:58:33