Chart.js图表仅展示旧数组值及首尾值NaN问题求助
解决Chart.js图表同步更新与首尾NaN值问题
问题1:图表未同步更新
原因:浏览器默认会缓存fetch请求结果,即使后端更新了Swerte.txt,前端拿到的还是旧缓存数据。
解决:在fetch请求中添加缓存控制参数,强制获取最新文件。
问题2:图表首尾值显示NaN
原因:Swerte.txt内容包含方括号[],手动拆分字符串时会把[53和30]当成有效元素,转换为数字时失败,出现NaN。
解决:直接用JSON.parse()解析整个txt内容,因为它本身就是合法的JSON数组格式,自动处理括号和逗号转换。
修改后的完整代码
<button id="submit1" type="button">Graph aktualisieren</button> <div style="width:800px; margin:0 auto;" class="Simulation"> <br><br><br> <canvas id="graph" style="width:100%;max-width:600px"></canvas> <script> let chartInstance = null; // 全局存储图表实例,避免重复创建 // 点击按钮更新图表 submit1.onclick = function () { // 强制不缓存,获取最新的Swerte.txt fetch("Swerte.txt", { cache: 'no-store' }) .then(function (response) { return response.text(); }) .then(function (txt) { // 直接解析txt为数字数组,自动处理[]和逗号 let yValues = JSON.parse(txt); // 检查数据长度是否匹配X轴的24个标签 if (yValues.length !== 24) { console.warn("数据长度不匹配,需要24个数值"); return; } const xValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]; // 销毁旧图表实例,避免叠加显示 if (chartInstance) { chartInstance.destroy(); } // 创建新图表 chartInstance = new Chart("graph", { type: "line", data: { labels: xValues, datasets: [{ fill: false, lineTension: 0, backgroundColor: "rgba(0,0,255,1.0)", borderColor: "rgba(0,0,255,0.1)", data: yValues }] }, options: { title: { display: true, text: 'Ergebniss Epidemie-Simulation:' }, legend: {display: false}, scales: { yAxes: [{ ticks: {min: 1}, scaleLabel: { display: true, labelString: 'Infizierte' } }], xAxes: [{ scaleLabel: { display: true, labelString: 'Tage' } }] } } }); }) .catch(function (error) { console.error("加载或解析数据出错:", error); }); }; </script> </div>
额外优化说明
- 添加了错误捕获
catch块,方便排查请求失败或数据格式错误的问题。 - 增加数据长度校验,确保Y轴数据和X轴的24个日期标签一一对应,避免图表显示异常。
- 用全局变量存储图表实例,每次更新前销毁旧实例,解决多次点击按钮导致的图表叠加问题。
内容的提问来源于stack exchange,提问作者Crownen
相关产品推荐
相关产品推荐

