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

如何在Chart JS中用数据库Timestamp绘制温感时序图及排错

解决Chart.js中时间标签的Uncaught SyntaxError: Unexpected token :错误

嘿,这个问题我太熟了!你遇到的语法错误,根源在于没有给时间字符串加上引号就直接输出到JavaScript数组里。

咱们来拆解一下问题:你的PHP代码拼接出来的$timeIntervals是类似12:28:36,12:28:26,...的字符串,输出到JS的labels数组后就变成了:

labels: [12:28:36, 12:28:26, ...]

在JavaScript里,12:28:36这种带冒号的内容会被当成非法的标识符,浏览器自然就抛出Uncaught SyntaxError: Unexpected token :的错误了。

两种靠谱的解决方案

方案一:手动给时间字符串加引号

修改PHP里的拼接逻辑,给每个时间值包裹单引号(避免和JS的双引号冲突):

// 初始化变量
$tempValues = "";
$timeIntervals = "";

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $tempValue = $row['Temperature'];
        $timeInterval = $row['TIME'];
        $tempValues .= $tempValue . ',';
        // 给时间字符串加上单引号
        $timeIntervals .= "'" . $timeInterval . "',";
    }
    $tempValues = trim($tempValues, ",");
    $timeIntervals = trim($timeIntervals,"," );
}

这样输出到JS的labels数组就会变成合法的字符串数组:

labels: ['12:28:36', '12:28:26', ...]

方案二:用JSON格式传递数据(更推荐)

手动拼接字符串很容易踩坑,比如遇到特殊字符(引号、换行)就会出问题。更稳妥的方式是用PHP的json_encode把数组转成JSON格式,直接传递给JS:

首先修改PHP部分,用数组收集数据:

// 初始化数组
$tempValues = [];
$timeIntervals = [];

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $tempValues[] = $row['Temperature'];
        $timeIntervals[] = $row['TIME'];
    }
}

// 转成JSON格式
$tempJson = json_encode($tempValues);
$timeJson = json_encode($timeIntervals);

然后在JS里直接使用这些JSON数据:

var myChart = document.getElementById('myChart').getContext('2d');
var data = {
    datasets: [{
        data: <?php echo $tempJson ?>,
        backgroundColor: 'transparent',
        borderColor:'rgba(255,99,132)',
        borderWidth:5,
        label: 'Temperature in degree'
    }],
    labels: <?php echo $timeJson ?>
};
var particleChart = new Chart(myChart, {
    type:'line',
    data: data
});

json_encode会自动处理所有字符串的引号和转义,生成完全符合JS语法的数组,从根源上避免这类语法错误。

小提示

以后PHP和JS之间传递数据,优先用JSON格式,不仅能避免语法问题,还能处理更复杂的数据结构(比如多维数组、对象),省心又靠谱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:00:33