jQuery Ajax显示数据

时间:2011-05-23 05:17:33

标签: javascript ajax

假设我有一个页面随着时间的推移缓慢地返回一堆数据。比如,这个例如:

<?php

$iTime = time();

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

?>

我希望显示所有数据。因此它会更新“直播”。如同,一旦发送了一行数据,它将允许我解析数据并显示它?

有没有办法通过jquery来做到这一点? 如果以前曾经问过这件事我很抱歉

感谢您的时间! :)

3 个答案:

答案 0 :(得分:2)

当然,建立基本的彗星式长期民意调查非常简单:

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 :(得分:1)

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

答案 2 :(得分:0)

嗯,你正在达到HTTP协议本身的限制,所以这不是jQuery,而是更多关于web编程。如果你真的需要实时推送,那么一个不同的协议更适合,比如XMPP(几个大玩家使用,如Google Wave)。

然而,使用jQuery我会在低延迟,低功耗资源上使用正常轮询来完成工作(很容易创建正确使用HTTP缓存的静态资源,依靠REST来指导你),所以类似的东西;

  1. setTimeout('myPoll(“http:// my_feed”)',500);
  2. my_feed使用HTTP缓存作为静态手段(如果需要,可能基于每个用户)