前端页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>echarts示例</title>
<script src="jquery.min.js"></script>
<script type = "text/javascript" src = "echarts.min.js" ></script>
</head>
<body>
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
// 初始化图表选项
myChart.setOption({
title: {
text: 'ECharts 数据异步加载示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: []
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: []
}]
});
function fetchData() {
$.ajax({
url: 'api/echarts/demo/', // 改为你的数据接口地址
dataType: 'json',
success: function(data) {
// 假设返回的数据格式如下:
// {
// categories: ["衬衫", "羊毛衫", ...],
// values: [5, 20, ...]
// }
myChart.setOption({
xAxis: {
data: data.categories
},
series: [{
name: '销量',
data: data.values
}]
});
},
error: function(xhr, type, errorThrown) {
// 处理错误
}
});
}
// 设置定时器,定期更新数据
setInterval(function () {
fetchData(); // 调用获取数据的函数
}, 5000); // 5000毫秒即5秒钟更新一次数据
</script>
</body>
</html>
跨域问题,依然采用nginx代理。
后端代码
from django.http import HttpResponse
import json
def EchartsDemo(request):
data = {}
categories = ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
values = [50, 20, 36, 10, 10, 20]
data['categories'] = categories
data['values'] = values
print("echerts=",data)
return HttpResponse(json.dumps(data), content_type="application/json")
展示效果: