假设我有一个页面随着时间的推移缓慢地返回一堆数据。比如,这个例如:
<?php
$iTime = time();
while(time()-$iTime < 10 ) {
echo "Hello world";
echo str_repeat( ' ', 1024 ) . "<br />";
flush( );
sleep(3);
}
?>
我希望显示所有数据。因此它会更新“直播”。如同,一旦发送了一行数据,它将允许我解析数据并显示它?
有没有办法通过jquery来做到这一点? 如果以前曾经问过这件事我很抱歉
感谢您的时间! :)
答案 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)