本地服务器JSON数据接入Chart.js折线图数据不显示问题求助
问题分析与修正方案
核心问题
- 图表初始化时机错误:图表初始化代码写在了请求成功的判断逻辑之外,导致HTTP请求还没返回数据就执行渲染,此时
AUDL和AUDS要么未定义,要么没有有效数据。 - JSON数据解析错误:返回的JSON是多层嵌套的数组+对象结构,你没有正确提取出图表需要的纯数值数组。
- 变量作用域问题:
AUDL和AUDS在请求成功的代码块内声明,外部的图表代码无法确保能拿到有效值。
修正后的代码
var xmlhttp = new XMLHttpRequest(); var url = "http://localhost:3000/AUDcotdata"; xmlhttp.open("GET", url, true); xmlhttp.send(); xmlhttp.onreadystatechange = function(){ if(this.readyState == 4 && this.status == 200){ var data = JSON.parse(this.responseText); console.log(data); // 正确解析嵌套的JSON结构 const dataItem = data[0]; // 取数组中的第一个对象 // 提取LONG数据:先取数组内的对象,再把对象值转为纯数值数组 const longDataObj = dataItem.LONGDEALERINTERMEDIARY[0]; const AUDL = Object.values(longDataObj); // 提取SHORT数据,逻辑同上 const shortDataObj = dataItem.SHORTDEALERINTERMEDIARY[0]; const AUDS = Object.values(shortDataObj); // 确保拿到数据后再初始化图表 const AUDlinecharttop = document.getElementById('fxlinecharttopAUD').getContext('2d'); const AUDlinechart1 = new Chart(AUDlinecharttop, { type: 'line', data: { labels: ['1', '2', '3', '4', '5', '6','7','8','9','10'] , datasets: [{ label: "Short", data: AUDS, backgroundColor: ['rgba(255, 99, 132, 0.2)'], borderColor: ['rgba(255, 99, 132, 1)'], borderWidth: 4, }, { label: "Long" , data: AUDL, backgroundColor: ['rgba(75, 192, 192, 0.2)'], borderColor: ['rgba(75, 192, 192, 1)'], borderWidth: 4 }], }, options: { responsive: true, // 修正为布尔值,原字符串"true"不符合要求 plugins: { title: { color: "white", display: true, text: 'Positions (AUD)', }, legend: { display: true, labels: { // 修正legend颜色配置位置,需放在labels下 color: "white" } } }, maintainAspectRatio: false, elements: { line: { fill: true, tension: 0.2 } }, scales: { y: { ticks: { color: "white" }, beginAtZero: true, }, x: { ticks: { color: "white" }, grid: { display: false } } } } }); } }
额外注意事项
- 你的JSON数据最后有一个多余的逗号(
SHORTDEALERINTERMEDIARY数组末尾的逗号),虽然部分浏览器能兼容解析,但建议后端修正这个格式错误,避免潜在的解析问题。
内容的提问来源于stack exchange,提问作者kiestuthridge23
相关产品推荐
相关产品推荐

