You need to enable JavaScript to run this app. 如何不刷新网页,定时调用PHP动态更新div背景色展示服务器状态
优惠活动
大模型
产品
解决方案
定价
更多

如何不刷新网页,定时调用PHP动态更新div背景色展示服务器状态

无需刷新自动更新服务器状态显示的实现流程

初始需求

目标是实现一个固定高度的div,用绿色、红色背景色区分服务器运行状态:背景色由PHP判断的状态变量决定,最初的实现刷新页面时可以正常完成颜色切换,但需要实现无需手动刷新页面,定时自动拉取最新状态更新div背景色。

最初的基础实现代码

<!DOCTYPE HTML>
<html>
<head>
<h1>Measurements - graphs</h1>
<?php
function getStatus() {
    $status = "#008000";
    $latestFile = '/my/web/logs/logging_rotation.out';
    
    if (file_exists($latestFile)) {
        $fileTime = filectime($latestFile);
        $now = microtime(true);
        $timediff = $now - $fileTime;
    }
    if ($timediff < 60) {
        $status = "#008000";
    } else {
        $status = "#FF0000";
    }
    return $status;
}
?>
<div style="height: 20px; background-color: <?php echo getStatus()?>;">Server status</div>
</head>
<body>
</body>
</html>

调试过程中遇到的问题

最初尝试用前端fetch实现无刷新请求时,写的状态拉取逻辑完全没有生效:

  • 预期运行的doSomething()函数没有触发,连提前写好的console.log测试输出都看不到
  • 当时尝试两种方式排查:一是浏览器直接重载对应的PHP页面,二是在服务器上执行php mypage.php > test.html导出静态页面查看,两种方式都拿不到预期的运行结果,一度不清楚这类PHP动态页面的正确调试方式。
  • 最终定位到两个核心问题:
    • 请求的status.php接口路径配置错误,使用相对路径导致请求资源404,改成站点根目录的绝对路径/status.php之后,请求才能正常到达后端
    • setInterval的调用方式有误,调整成正确的函数引用形式后,定时任务才能按周期触发

可正常运行的落地实现

精简版实现

逻辑无冗余,代码量最少:

  • 前端页面内嵌定时拉取逻辑:
<script>
  setInterval(function() {
    fetch('/status.php')
      .then(response => response.text())
      .then(function(text){
        document.getElementById('serverStatus').style.backgroundColor = text;
      })
  }, 1000) // *定时间隔单位为毫秒*
</script>

<h2>Measurements - graphs</h2>
<div id="serverStatus" style="height: 20px;">Server status</div>
  • 独立的后端接口status.php逻辑:
<?php
    $status = "#008000";
    $latestFile = '/my/web/logs/logging_rotation.out';
    if (file_exists($latestFile)) {
        $fileTime = filectime($latestFile);
        $now = microtime(true);
        $timediff = $now - $fileTime;
    }
    if ($timediff < 60) {
        $status = "#008000";
    } else {
        $status = "#FF0000";
    }
    exit($status); // 直接返回状态值给前端
?>

异步风格实现

采用async/await语法,适合学习现代前端异步编程逻辑:

<script>
    async function doSomething() {
        const url = "/status.php";
        await fetch(
            url,
            {
                method: "POST",
                body: new URLSearchParams("function=serverStatus")
            }
        )
        .then(response => response.text())
        .then((response) => {
            console.log(response);
            document.getElementById('serverStatus').style.backgroundColor = response;
        })
        .catch(err => console.log('请求出错', err));
    };
    setInterval(doSomething, 1000);
</script>

<h2>Measurements - graphs</h2>
<div id="serverStatus" style="height: 20px;">Server status</div>

方案适配说明

两套方案都可以稳定实现需求:通过判断日志文件最近修改时间与当前时间的差值是否小于60秒,识别服务器运行状态,自动更新div背景色。其中精简版的实现逻辑直观、代码量少,异步版本更贴合现代前端开发的写法,适合有学习需求的场景。

内容的提问来源于stack exchange,提问作者FotisK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 11:15:00