实现自重置 XMLHttpRequest 对象

2024-01-21

我正在尝试使用 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)自己的事件处理程序(进程)中删除对象(xhr),就像这里的情况一样。特别是因为处理程序中的“this”绑定到一个对象(XHR),该对象包含我试图删除的对象(xhr)。 有点圆形!

有人可以帮忙吗?上面的例子是我能得到的最接近的例子。


只需使用 jquery 并执行以下操作:

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

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

My slosh http://github.com/dustin/slosh示例就是这样做的(因为它几乎是一个彗星服务器)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

实现自重置 XMLHttpRequest 对象 的相关文章