XMLHttpResponse オブジェクトを使用して、コメット スタイルのロング ポーリング接続を実装しようとしています。アイデアは、データが利用可能になったときにデータを送信するサーバーへのオープン接続を維持することです (偽のプッシュ)。XHR オブジェクトが完了するとすぐに、新しいデータを待機するために新しいオブジェクトを生成する必要があります。
以下は、機能するソリューションの概要を示すコードのスニペットですが、コメントが言うように、取り除く必要があるタイムアウトのためだけです。
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) にバインドされているためです。なんか円形!
誰でも助けることができますか?上記の例は、私が得ることができる最も近いものです。