gpt4 book ai didi

javascript - PHP 使用 javascript 每 3 秒刷新一次数据

转载 作者:行者123 更新时间:2023-11-29 08:12:14 25 4
gpt4 key购买 nike

我试图每三秒读取一次数据而不重新加载页面。我的脚本中缺少一些内容,因为在我重新加载页面之前它不会刷新数据。提前致谢。

<html>
<head>
<meta charset="UTF-8">
<title>Testing</title>
<!-- below script is for jquery -->
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript">
function refreshData(){
$.ajax({
url: 'localhost/index1.php',
type:"POST",
data:"dataPost",
success: function(data){
document.getElementById("dataPost").innerHTML = data;

//render the dynamic data into html
}
});
}
setInterval(refreshData, 3000);
</script>
</head>
<div id="dataPost">
<?php
$conn = mysql_connect('localhost','user','password');
$db = mysql_select_db('db',$conn);
$query = "select * from table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['data1']."<br/>";
}
?>
</div>
</html>

最佳答案

我同意@Axel,但由于Ajax是一个异步函数,即使您的PHP代码位于外部文件中,您仍然会遇到计时问题。

基本上,您无法知道 Ajax 调用需要多长时间才能完成(想象一下服务器正忙或关闭),因此手动将间隔设置为每 3 秒是没有意义的。您需要将其设置为距上次完成后 3 秒。

在您的 php 上 - 只需将脚本放入外部文件(即 script.php)即可。

在你的 JavaScript 上 -

  1. 将 setInterval() 移至 success 事件内,并使用改为 setTimeout()。
  2. 创建 document.ready 事件并从中调用refreshData()。

      <script type="text/javascript">
    $(document).ready(function() {
    refreshData();
    });
    function refreshData(){
    $.ajax({
    url: 'localhost/script.php',
    type:"POST",
    data:"dataPost",
    success: function(data){
    document.getElementById("dataPost").innerHTML = data;//why not use $('#dataPost').html(data) if you're already using jQuery?
    setTimeout(refreshData, 3000);//will make the next call 3 seconds after the last one has finished.
    //render the dynamic data into html
    }
    });
    }

    </script>

您的 PHP 文件 (script.php) 将如下所示:

<?
$conn = mysql_connect('localhost','user','password');
$db = mysql_select_db('db',$conn);
$query = "select * from table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo $row['data1']."<br/>";
}
?>

希望这有帮助。

P.S 正如许多人指出的那样,mysql_connect 已被弃用,因此最好开始使用 MySQLi 或 PDO。

关于javascript - PHP 使用 javascript 每 3 秒刷新一次数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21342577/

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