jQuery Ajax 实时显示数据

11

假设我有一个页面,会逐渐慢慢地返回一大堆数据。比如,就像这个例子:

<?php

$iTime = time();

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

?>

我希望能够实时显示所有收到的数据。也就是说,一旦发送了一行数据,它将允许我解析数据并显示它?

有没有通过jquery实现这个功能的方法?如果以前已经问过这个问题,请原谅。

感谢您的时间! :)


我认为你不想在服务器端使用 sleep(),那只会减慢响应速度。那么,在客户端使用 setTimeout() 'loop' 通过 AJAX 分段请求数据怎么样?或者(我更喜欢的方式)一次性返回所有数据,但将其存储在 JavaScript 数组中,然后使用 setTimeout() 逐步显示数组中的每个元素呢? - nnnnnn
1
这只是一个示例脚本,让它运行很长时间。我的实际脚本不使用sleep。 :) - dab
3个回答

2
当然,构建一个基本的comet式长轮询相当简单:
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);
           }
       });
 }

1

看一下ajax-http-stream jquery插件。它扩展了jquery ajax调用,以接受从后端流式传输的彗星样式数据,并在新数据到达时调用函数OnDataRecieved


嗯,插件对我没用:( 但这基本上就是我在寻找的。 - dab

0

嗯,你遇到了HTTP协议本身的限制,所以这与jQuery关系不大,更多涉及到了Web编程。如果你确实需要实时推送,那么使用不同的协议可能更合适,比如XMPP(像Google Wave这样的大公司都在使用)。

然而,对于jQuery,我会使用低延迟、低功耗的资源进行正常轮询来完成任务(可以轻松创建使用HTTP缓存的静态资源,并依赖REST指导你),类似于以下方式:

  1. setTimeout('myPoll("http://my_feed")', 500);
  2. my_feed作为一个静态资源使用HTTP缓存(如果有必要,可以根据每个用户设置)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接