How to dynamically load data in Echarts?
One common method of dynamically loading data in ECharts is by using technologies such as Ajax or WebSocket.
- Include the ECharts JavaScript file, as well as the necessary theme and renderer files, in the HTML document.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts 动态加载数据示例</title>
<script src="echarts.min.js"></script>
<script src="echarts-theme.js"></script>
<script src="echarts-renderer.js"></script>
</head>
<body>
<div id="chart" style="width: 600px; height: 400px;"></div>
<button onclick="loadData()">加载数据</button>
<script>
// 初始化 ECharts 实例
var chart = echarts.init(document.getElementById('chart'));
// 定义图表的配置项和数据
var option = {
// 图表的配置项
// ...
};
// 加载数据的函数
function loadData() {
// 使用 Ajax 请求获取数据
// 这里假设数据请求的 URL 为 data.json
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
// 更新图表的数据
option.series[0].data = data;
// 使用刚指定的配置项和数据显示图表
chart.setOption(option);
}
};
xhr.send();
}
</script>
</body>
</html>
- The file named data.json
[10, 20, 30, 40, 50]
- Load data.
- Choose an option.
The code examples above only provide a simple way to dynamically load data, modifications may be needed based on specific requirements in actual applications.