为了更清楚起见,我在这里打开一个新线程,因为我们解决了第一个问题,感谢你们:)
我们有一个人工智能,它不断地编写文本并将其推送到MySQL bdd中。我们想把这段文字作为一个无限的在线发布来展示。我们希望看到它写作,就像你在屏幕上写文本一样,所以我们尝试了这个:
<!DOCTYPE html>
<head>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="myTable"></div>
<script type="text/javascript">
function page_refresh() {
$.ajax({
url : 'getData.php',
type : 'GET',
success : function(data) {
$('#myTable').html(data);
},
error : function(request,error)
{
alert("Request error : "+JSON.stringify(request));
}
});
}
var period = 100; //NOTE: period is passed in milliseconds
setInterval(page_refresh, period);
</script>
</body>
对于获取数据.php
<?php
$dbhandle = new PDO("mysql:host=localhost;dbname=writing", "root", "*********");//this connects to your mysql table
$sql = "SELECT text, id, date FROM table_02 ;"; //thise is your query, where you select what data you want from the table
$query = $dbhandle->prepare($sql);
if ($query->execute() == FALSE)
{ die("Query error: " . implode($query->errorInfo(), ' ')); } //this is a measure to close the connection if there is an error
echo('<table>');
echo('<tr><th>Test</th></tr>');
while ($row = $query->fetch()) {
echo('<tr>');
##echo('<td>'.$row ['id'].'</td>');
##echo('<td>'.$row ['date'].'</td>');
echo('<td>'.$row ['text'].'</td>');
echo('</tr>');
}
echo('</table>');
?>
这
var period = 100; //NOTE: period is passed in milliseconds
setInterval(page_refresh, period);
似乎在如此低的时间下效果不佳,看起来它只是用我们拥有的测试数据刷新整个页面。此外,由于某些原因,页面在显示数据之前会保持空白几秒钟。有没有更有趣的方法可以做到这一点?
你有使用WebSockets的知识吗?创建此技术是为了取代服务器的定期轮询以获取更新。服务器可以将更改推送到客户端,而不是从客户端轮询。您可以在此处阅读更多相关信息
正如我在评论中所说,100ms 不会让您的数据库获取 Web 服务的数据以及 Web 服务将数据中继到您的前端。仅当您处理的数据量较少,并且 Web 服务服务器驻留在数据库服务器的同一台计算机(或靠近该计算机(时,此操作才能正常工作。
现在,对于"更有趣的方式"。
您可以每 100 毫秒获取一次所需的数据,没问题,但您不能尝试立即显示它(我已经在我的评论中解释了原因(。相反,构建一个队列和一个函数来显示它的第一个元素。当函数返回时,是时候从队列中弹出第一个元素并显示下一个元素了。这样,您可以确保文本始终正确显示并按插入顺序显示。