实现自我复位XMLH​​tt prequest对象对象、自我、tt、XMLH

2023-09-10 18:25:46 作者:寶貝,妳傷得我好重

我想实现一个彗星的风格,采用了XMLHtt presponse对象长轮询连接。 我们的想法是要保持一个开放的连接,它发送数据时,它可用(伪造推送)的服务器。一旦XHR对象完成,我需要生成一个新等待任何新的数据。

I'm trying to implement a comet style, long polling connection using an XMLHttpResponse object. The idea is to maintain an open connection to a server which sends data when it is available (faking push). As soon as the XHR object completes, I need to spawn a new one to wait for any fresh data.

下面是code片段,概述一个解决方案,工程,但正如评论说,只有超时,我需要摆脱因。

Below is a snippet of code which outlines a solution that works but, as the comment says, only because of a timeout which I need to get rid of.

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)为是这里的情况。特别是因为这个内的处理程序绑定到一个对象(XHR),它包含对象(XHR)我想删除。 有点圆!

I think the problem might be that you can't delete an object (xhr) from it's own event handler (process) as is the case here. especially because the 'this' within the handler is bound to an object (XHR) which contains the object (xhr) I'm trying to delete. Kinda circular!

谁能帮助?上面的例子是最接近我可以得到的。

Can anyone help? The above example is the closest I can get.

推荐答案

只需使用jQuery和做这样的事情:

Just use jquery and do something like this:

  function getData() {
    $.getJSON(someUrl, gotData);
  }

  // Whenever a query stops, start a new one.
  $(document).ajaxStop(getData, 0);
  // Start the first query.
  getData();

我的晃动例子做到这一点(因为它是pretty的很多彗星的服务器)。

My slosh examples do this (since it's pretty much a comet server).