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

Chart.js引入动态获取变量后饼图不显示问题求助

问题根源:错误地将数组转为字符串导致Chart.js无法识别

嘿,我一眼就揪出问题所在了——你用JSON.stringify()处理后端返回的数组数据,但Chart.js需要的是原生数组类型,不是字符串!

为什么会出现这个情况?

你的Python后端返回的Name、Duration、color本身就是列表(对应前端的数组),但你在前端用JSON.stringify()把它们转换成了字符串格式。举个直观的例子:

  • 后端返回的Name是 ["项目A", "项目B"]
  • 经过JSON.stringify()后变成了 "[\"项目A\",\"项目B\"]"

Chart.js的labels和data字段需要接收数组,拿到字符串后无法解析成有效的数据项,自然就渲染不出饼图了。而且因为这不是JavaScript语法错误,所以控制台不会抛出报错信息。

修复方案

直接去掉所有的JSON.stringify()调用,直接使用后端返回的原生数组:

修改后的前端代码片段:

fetch("/Pie").then(response => response.json()).then(function (response) {
    if (response == null) {
        console.log("returned nothing");
    } else {
        console.log(response.Name);
        console.log(response.Duration);
        console.log(response.color);
        // 去掉JSON.stringify,直接赋值原生数组
        Name = response.Name;
        Duration = response.Duration;
        Color = response.color;
        var data = {
            labels: Name,
            datasets: [{
                label: "Data",
                fill: true,
                backgroundColor: gradientStroke,
                borderColor: Color,
                borderWidth: 2,
                borderDash: [],
                borderDashOffset: 0.0,
                pointBackgroundColor: '#d048b6',
                pointBorderColor: 'rgba(255,255,255,0)',
                pointHoverBackgroundColor: '#d048b6',
                pointBorderWidth: 20,
                pointHoverRadius: 4,
                pointHoverBorderWidth: 15,
                pointRadius: 4,
                data: Duration
            }]
        };
        var myChart = new Chart(ctx, {
            type: 'doughnut',
            data: data,
            options: gradientChartOptionsConfigurationWithTooltipPurple
        });
    }
});

额外验证小技巧

你可以在控制台加一行打印,确认数据类型是否正确:

console.log(typeof response.Name);

如果输出是object(数组的typeof结果就是object),说明数据是正确的数组类型;如果输出是string,就说明之前的JSON.stringify()把它转成了字符串,这就是问题的核心。

另外顺便确认下ctx变量是否在fetch回调之外已经正确获取到了canvas元素的上下文,比如:

const ctx = document.getElementById('your-chart-canvas-id').getContext('2d');

不过你之前把data放在函数外能正常显示,这一步应该没问题,但可以作为后续排查的备选点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:36:39