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

如何在Chart.js折线图中展示双JSON数据集?解决undefined报错

解决Chart.js双折线图数据获取报错问题

我来帮你搞定这个问题!首先看你遇到的Cannot read property 'current_week' of undefined错误,核心原因有两个:

问题1:循环方式错误

你用了for(var i in data),但这里的data是包含current和last两个数组的对象,for...in会遍历对象的属性名(也就是"current"和"last"),而不是数组的索引。当i是"current"时,data.current["current"]自然是undefined,就会抛出错误。

问题2:两个数据集长度不一致

你的current数组只有3个元素,last数组有7个,但图表的labels是7个(周一到周日),直接按索引取值会导致超出数组长度的情况,同样会报错。

修正后的完整代码

$(document).ready(function() {
    $.ajax({
        url : "http://localhost/r6team-new/admin/includes/stats/website-weekly-stats.php",
        type : "GET",
        dataType: 'json', // 直接指定返回类型为JSON,避免手动解析
        success : function(data) {
            console.log(data);
            var current_week = [];
            var last_week = [];
            // 按labels的长度(7天)循环,确保每个标签都有对应数据
            const daysCount = 7;
            for(let i = 0; i < daysCount; i++) {
                // 如果current数组对应索引有数据,取current_week,否则补null(图表会留空)
                current_week.push(data.current[i]?.current_week ?? null);
                // 同理处理last_week
                last_week.push(data.last[i]?.last_week ?? null);
            }
            console.log(current_week);
            console.log(last_week);
            
            var visitorsChart = {
                labels: ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO'],
                datasets: [{
                    type : 'line',
                    data : current_week,
                    backgroundColor : 'transparent',
                    borderColor : '#007bff',
                    pointBorderColor : '#007bff',
                    pointBackgroundColor: '#007bff',
                    fill : false
                }, {
                    type : 'line',
                    data : last_week,
                    backgroundColor : 'transparent', // 修正拼写错误:tansparent → transparent
                    borderColor : '#ced4da',
                    pointBorderColor : '#ced4da',
                    pointBackgroundColor: '#ced4da',
                    fill : false
                }]
            };
            
            var ctx = $("#visitors-chart");
            var LineGraph = new Chart(ctx, {
                data: visitorsChart,
                // 可以加上配置项,比如设置折线图的行为
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        },
        error: function(xhr, status, error) {
            console.error("AJAX请求失败:", error); // 加上错误捕获,方便排查问题
        }
    });
});

关键改动说明

  1. 指定dataType: 'json':让jQuery自动把返回的字符串解析成JSON对象,不用手动JSON.parse(data)。
  2. 按固定天数循环:因为图表是7天的数据,所以循环7次,确保每个标签都有对应的数据点。
  3. 可选链操作符?.和空值合并运算符??:安全访问数组元素,当索引超出数组长度时,自动补null,避免报错,同时图表会在没有数据的位置留空。
  4. 修正拼写错误:把'tansparent'改成正确的'transparent',避免样式失效。
  5. 添加错误捕获:AJAX请求失败时可以在控制台看到错误信息,方便排查。

这样修改后,就能正常渲染两条折线啦,即使两个数据集长度不一样也能正确显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:27:29