You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AJAX调用更新Google Gauge仪表盘图表并解决相关报错

Google Gauge仪表盘AJAX更新问题修复方案

现存问题

  • 缺少jQuery依赖:你遇到的ReferenceError: $ is not defined报错,核心原因是代码中使用了jQuery封装的$.ajax方法,但页面未引入jQuery库,浏览器无法识别$符号。
  • 后端数据返回不规范:当前gaugechart.php直接输出普通数组文本,未设置JSON响应头,也没有做格式校验,前端无法直接匹配Google Charts的格式要求,容易出现解析错误。
  • 图表实例重复创建:每次定时请求成功后都会新建Gauge实例,长期运行会产生冗余的内存占用。

修复代码

前端页面代码(index3.php)

首先引入jQuery依赖,同时优化图表实例逻辑:

<head>
  <meta charset="utf8" />
  <title>Gauge</title>
  <!-- 引入jQuery依赖 -->
  <script src="https://cdn.staticfile.org/jquery/3.6.4/jquery.min.js"></script>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
    // 全局保存图表实例,避免重复创建
    let gaugeChart = null;
    google.charts.load('current', {
      callback: function() {
        drawChart();
        setInterval(drawChart, 10000);

        function drawChart() {
          $.ajax({
            url: 'gaugechart.php',
            type: 'get',
            dataType: 'json', // 声明预期返回JSON格式
            success: function(res) {
              var data = google.visualization.arrayToDataTable(res);
              // 复用图表实例
              if(!gaugeChart) {
                gaugeChart = new google.visualization.Gauge(document.getElementById('gauge_div'));
              }
              gaugeChart.draw(data, {
                width: 500,
                height: 200,
                minorTicks: 5
              });
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log(errorThrown + ': ' + textStatus);
            }
          });
        }
      },
      packages: ['gauge']
    });
  </script>
</head>
<body>
  <div id="gauge_div" style="width: 100%; height: 400px;" class="d-flex align-items-center justify-content-center mt-3"></div>
</body>
</html>

后端数据接口代码(gaugechart.php)

改用json_encode生成标准JSON格式,添加响应头声明:

<?php
// 声明返回JSON格式
header('Content-Type: application/json');
// 连接数据库
$con = mysqli_connect('localhost', 'root', '', 'adminpanel');
if (!$con) {
  echo json_encode([]);
  exit;
}
$sql = 'SELECT * FROM tbl_waterquality ORDER BY id DESC LIMIT 1';
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);

// 构造符合要求的数组
$chartData = [
  ["Label", "Value"],
  ["Temperature", (float)$row["temperature"]],
  ["pH", (float)$row["pH"]],
  ["DO", (float)$row["DO"]],
  ["Turbidity", (float)$row["Turbidity"]]
];

// 输出JSON格式数据
echo json_encode($chartData);
?>

验证步骤

  1. 确认数据库连接参数正确,tbl_waterquality表存在temperature、pH、DO、Turbidity四个字段
  2. 访问前端页面,打开浏览器开发者工具控制台,确认无报错
  3. 修改数据库中的最新数据,等待10秒查看仪表盘数值是否自动更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:06:01