我試圖實現一個使用XMLHttpResponse對象的彗星樣式,長查詢連接。 這個想法是保持一個開放的連接到服務器,當服務器可用時發送數據(僞造推送)。一旦XHR對象完成,我需要產生一個新的等待任何新的數據。實現自復位XMLHttpRequest對象
下面是一段代碼,其中概述了一個可行的解決方案,但正如評論所說,只是因爲我需要擺脫超時。
window.onload = function(){
XHR.init();
}
XHR = {
init: function() {
this.xhr = new XMLHttpRequest();
this.xhr.open("GET", "proxy.php?salt="+Math.round(Math.random()*10000), true);
this.xhr.onreadystatechange = this.process.bind(this);
this.xhr.send(null);
},
process: function() {
if(this.xhr.readyState == 4) {
// firebug console
console.log(this.xhr.responseText);
// ** Attempting to create new XMLHttpRequest object to
// replace the one that's just completed
// doesn't work without the timeout
setTimeout(function() { this.init() }.bind(this), 1000);
}
}
}
Function.prototype.bind = function(obj) {
var method = this;
return function() {
return method.apply(obj, arguments);
}
}
// proxy.php - a dummy that keeps the XHR object waiting for a response
<?php
$rand = mt_rand(1, 10);
sleep($rand);
echo date('H:i:s').' - '.$rand;
我認爲這個問題可能是你無法刪除它自己的事件處理程序(過程)的對象(XHR)如這裏的情況。尤其是因爲處理程序中的'this'綁定到一個包含我試圖刪除的對象(xhr)的對象(XHR)。 有點圓!
任何人都可以幫忙嗎?上面的例子是我能得到的最接近的例子。
這回答'如何做'問題,但不是'它是如何工作'的問題。 我將不得不在周圍的jQuery源中找出答案。具體來說,如何引發ajaxStop事件。 – meouw 2008-12-31 14:47:45