2012-05-07 21 views
1

我使用以下代碼掛接到XMLHttpRequest的開/發送方法:鉤入的XMLHttpRequest打開和發送方法

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

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, 
     params: lastParams, 
     responseText: self.responseText 
     }; 
     console.log(response); 
    } 
    }, false); 
    open.call(this, method, uri, async, user, pass); 
}; 

它是在一次單一的AJAX請求的情況下正常工作。

當多個ajax請求一次觸發時,則lastParams可能包含錯誤的數據(意味着lastParams可能包含來自其他ajax請求的數據)。我想唯一地將lastParams與請求的其他屬性相關聯?

XMLHttpRequest中是否有任何id屬性,以便我可以唯一標識ajax請求實例?

在此先感謝。

+1

既然你已經延長了原型......你爲什麼不加** ** lastParams的原型? – McGarnagle

+0

根據您的示例,我的問題是:「您是否正確理解如何正確使用XMLHttpRequest?」爲什麼你需要重寫'send'和'open'? –

回答

1

爲了將某些數據與指定的XMLHttpRequest實例唯一關聯,您可以簡單地將屬性添加到XMLHttpRequest實例中並將數據保存到屬性中。例如:

// generating data for request 
var data=generateData(); 

// sending data 
var xhr=new XMLHttpRequest(); 
xhr.open("POST","/yourpage.php",true); 
xhr.onreadystatechange=function(event){ 
    if(this.readyState===4){ 
    console.log(this.mySendedData); 
    } 
}; 
/** if you need to preserve 'data' variable value for each xhr **/ 
xhr.mySendedData=data; 
/***************************************************************/ 
xhr.send(data); 
0

爲什麼不把「lastParams」作爲數組,而你總是推,而不是每次覆蓋它的數據。

1

看一看https://github.com/jpillora/xhookdemos

//modify 'responseText' of 'example2.txt' 
xhook.after(function(request, response) { 
    if(request.url.match(/example\.txt$/)) { 
    response.text = response.text.replace(/[aeiou]/g,'z'); 
    } 
});