我试图实现一个使用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