1.准备一个div容器用来接收echarts
确保你的页面中有一个用于渲染图表的div元素,并且已经引入了ECharts库。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ECharts 异步数据加载示例</title> <!-- 引入 ECharts --> <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.0/echarts.min.js"></script> </head> <body> <div id="main" style="width: 600px;height:400px;"></div> <script src="your-script.js"></script> </body> </html>
2.JSON数据
{"time":["1","2","3","4","5","6","7"], "f1":["10","20","20","40","50","30","10"], "f2":["13","25","60","40","58","30","20"], "f3":["15","28","70","40","80","10","30"], "f4":["17","29","70","40","50","30","30"], }
3.在单独的JavaScript文件中编写逻辑,包括初始化图表、异步获取数据以及更新图表数据。
var myChart = echarts.init(document.getElementById('main')); $.ajax({ type: "get", async: true, url: "a.json", dataType: "json", success: function (data) { // 获取输入 JSON 对象的所有属性名称 const keys = Object.keys(data); // 过滤出所有以 'f' 开头并跟随数字的键 const featureKeys = keys.filter(key => /^f\d+$/.test(key)); // 找出最大的数字部分 let maxNum = 0; featureKeys.forEach(key => { const num = parseInt(key.substring(1), 10); // 去掉 'f' 后取数字部分 if (num > maxNum) { maxNum = num; } }); // 构造正则表达式,匹配从 f1 到最大数字的键 const regexPattern = new RegExp(`^f[1-${maxNum}]$`); // 指定图表的配置项和数据 var option = { title: { text: '多属性折线图示例' }, tooltip: { trigger: 'axis', position: function (pt) { return [pt[0], '10%']; } }, legend: { data: Object.keys(data).filter(key => regexPattern.test(key)) }, xAxis: { type: 'category', data: data.time }, yAxis: { type: 'value' }, series: [] }; // 循环遍历属性(除了 time),为每个属性创建一个折线系列 Object.keys(data).forEach(key => { if (regexPattern.test(key)) { option.series.push({ name: key, type: 'line', connectNulls: true, // smooth:true data: data[key].map((value, index) => { // 处理 null 值,避免绘图错误 return value !== null ? parseFloat(value) : null; }) }); } }); // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); } });