如何定期执行PHP引入文件获取数据实现页面无刷新更新时间值
解决方案
1. 修复time.php代码
原有代码执行ob_get_clean()后没有输出时间值,导致前端发起请求时无法拿到返回结果,优化修改后代码如下:
<?php error_reporting(0); ini_set('display_errors', 0); $conn=oci_connect('abcd', 'abcd', 'orcl'); $stid = oci_parse($conn, "***QUERY*******"); $r=oci_execute($stid); $time = ''; while ($row = oci_fetch_array($stid, OCI_BOTH)) { $time .= $row[0].","; } // 输出时间值供前端获取 echo $time; ?>
2. 修改index.php实现定时刷新
不需要依赖jQuery,用原生JS的fetch接口配合setInterval就能实现定期拉取最新时间,修改后代码如下:
<!DOCTYPE html> <html lang="en"> <body> <!-- 可选:添加DOM节点展示时间 --> <div id="time-display"></div> <script> var time = ''; // 定义拉取时间的方法 function fetchTime() { fetch('time.php') .then(res => res.text()) .then(res => { // 更新全局time变量 time = res; // 如果需要在页面展示,更新DOM内容 document.getElementById('time-display').innerText = time; }) } // 页面加载时先拉取一次 fetchTime(); // 每1000毫秒(1秒)拉取一次,可根据需求调整间隔时间 setInterval(fetchTime, 1000); </script> </body> </html>
如果你习惯用jQuery,把fetch部分替换为
$.get('time.php', function(res) { time = res; })即可,你之前用load()没生效是因为load()是用来将返回内容直接插入到指定DOM节点的,不适合用来给变量赋值。
内容的提问来源于stack exchange,提问作者jot
相关产品推荐
相关产品推荐

