springboot前后端分离怎么让echart拿到后台数据
时间: 2024-02-26 14:56:29 浏览: 35
要让 Echart 拿到后台数据,可以按照以下步骤操作:
1. 在后台编写接口,返回需要展示在 Echart 上的数据。可以使用 Spring Boot 提供的 @RestController 注解来实现。
2. 在前端页面中,使用 Ajax 或者 Axios 等工具向后台发送请求,获取数据。
3. 在获取到数据后,将数据传递给 Echart,并配置 Echart 的相关参数以展示数据。
以下是一个简单的示例代码,供您参考:
后台代码(Java):
```java
@RestController
@RequestMapping("/data")
public class DataController {
@GetMapping("/echart")
public List<Data> getEchartData() {
// 查询数据库或其他数据源,获取需要展示在 Echart 上的数据
List<Data> dataList = dataService.getDataList();
return dataList;
}
}
```
前端代码(HTML + JavaScript):
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Echart Demo</title>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.1.2/echarts.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div id="echart" style="width: 600px;height:400px;"></div>
<script>
$(function() {
// 向后台发送请求,获取需要展示在 Echart 上的数据
$.get('/data/echart', function(data) {
// 配置 Echart 的参数
var option = {
title: {
text: 'Echart Demo'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: data.map(function(item) { return item.name; })
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: data.map(function(item) { return item.value; })
}]
};
// 在页面上展示 Echart
var echart = echarts.init(document.getElementById('echart'));
echart.setOption(option);
});
});
</script>
</body>
</html>
```
在这个示例中,我们通过向 /data/echart 发送 GET 请求,获取需要展示在 Echart 上的数据。在获取到数据后,我们使用 Echart 的相关参数配置,将数据展示在页面上。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)