最近在学习echarts,看到官方给出的入门案例数据都是“写死”的,那么应该如何从后端获取数据并渲染到前端呢?试着写了一个小案例,通过ajax实现的,小白初学,欢迎指正
前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>ECharts</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/echarts/4.3.0/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'));
var names = [];
var nums = [];
draw();
function draw() {
$.ajax({
type: "post",
async: true,
url: "test",
dataType: "json",
success: function (results) {
if (results != null) {
names.push(results["names"])
nums.push(results["nums"])
myChart.setOption({
title: {
text: 'echarts从后端获取数据'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: names
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: nums
}
]
});
}
},
error: function (errorMsg) {
alert("图表请求数据失败!");
}
})
}
</script>
</body>
</html>
实体类(Goods)
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Goods {
private String names;
private int nums;
}
controller控制器
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class EchartsController {
@RequestMapping("/test")
@ResponseBody
public Goods echarts(){
Goods goods = new Goods();
goods.setNames("毛衣");
goods.setNums(20);
return goods;
}
}
|