我想显示所有传入的数据。所以它会“实时”更新。比如,一旦发送了一-6ren">
gpt4 book ai didi

javascript - jQuery Ajax 显示传入的数据

转载 作者:可可西里 更新时间:2023-11-01 02:46:56 26 4
gpt4 key购买 nike

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

<?php

$iTime = time();

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

?>

我想显示所有传入的数据。所以它会“实时”更新。比如,一旦发送了一行数据,它就会允许我解析数据并显示它?

有没有办法通过 jquery 做到这一点?如果之前有人问过这个问题,我深表歉意

感谢您的宝贵时间! :)

最佳答案

当然,构建一个基本的 cometd 式长轮询非常简单:

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);
}
});
}

关于javascript - jQuery Ajax 显示传入的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6093103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com