小编典典

jQuery Ajax显示数据

ajax

假设我有一个页面,该页面会随着时间的流逝缓慢地返回一堆数据。例如,例如:

<?php

$iTime = time();

while(time()-$iTime < 10 ) {
    echo "Hello world";
    echo str_repeat( ' ', 1024 ) . "<br />";
    flush( );
    sleep(3);
}

?>

我想显示所有数据,因此它将“实时”更新。就像这样,一旦发送了一行数据,它将允许我解析并显示数据吗?

有没有办法通过jQuery做到这一点?抱歉,以前是否有人问过这个问题

谢谢你的时间!:)


阅读 311

收藏
2020-07-26

共1个答案

小编典典

当然,建立一个基本的彗星风格的长轮询非常简单:

PHP:

<?php
    $data = null;
    while ($data ==  null)
    {
         $data = find_data($_REQUEST['last_update']); // This is up to you.
                    // Although you may do a DB query, that sort of breaks the model
                    // from a scalability perspective.  The point in this kind of
                    // operation is to rely on external data to know that it needs to 
                    // update users, so although you can keep your data in a DB, you'll
                    // want a secondary storage mechanism to keep from polling it.
                    //
                    // Conceptually, you'd put new information into this data storage
                    // system when something changes (like new data from an external
                    // source.  The data storage system could check to see if a file
                    // has been updated or if there is new data in something like a
                    // memcached key.  You'd then consume the data or otherwise 
                    // mark it as used.
         sleep(5);
    }
    echo json_encode($data);

JavaScript:

 function setListener()
 {
      $.ajax({
           url: 'updater.php',
       dataType: 'json',
       success: function(data, status, xhr) 
           {
              // do something, such as write out the data somewhere.
              setListener();
           },
       error: function()
           {
               setTimeout(setListener,10000);
           }
       });
 }
2020-07-26