echarts柱状图动态获取后台数据(二)
程序员文章站
2022-05-31 13:29:38
...
1.效果图如下:
2.引入前端样式:(前端主要是bootstrap的样式。可以去官网下载哈)
3.前端代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dashboard</title>
<link rel="stylesheet" href="../static/assets/css/bootstrap.min.css">
<script src="../static/jquery/jquery-3.2.1.min.js"></script>
<script src="../static/bootstrap/js/bootstrap.js"></script>
<script src="../static/js/echarts.min.js"></script>
</head>
<body>
<div id="histogram" style= "width:1200px; height:450px;"></div>
<script>
$(function() {
echartsFunc();
});
var echartsFunc = function(){
var myChart = echarts.init(document.getElementById('histogram'));
var jsonyDX = [];
var jsonyDY = [];
$.ajax({
url: '/dashboard/getDashList',
dataType : 'json',
type : 'POST',
cache: false,
async: false,
success: function(data) {
var json = data;
if (json.length > 0) {
for (var i = 0; i < json.length; i++) {
jsonyDX.push(json[i].prohectName);
jsonyDY.push(json[i].lastTime);
}
alert("json2-------"+JSON.stringify(jsonyDX));
var option = {
tooltip: {
trigger: 'axis', //坐标轴指示器,坐标轴触发有效
axisPointer : { //坐标轴指示器,坐标轴触发有效
type : 'shadow' //默认为直线,可选为:'line' | 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis : {
type : 'category',
data : jsonyDX,//jsonyDX代表动态从后台数据库取值
axisTick: {
alignWithLabel: true
},
axisLabel: {
interval:0,
rotate:38, //代表逆时针旋转45度
},
},
yAxis : {
type : 'value'
},
series : [{
data : jsonyDY,
type : 'bar',
barWidth : 75, //设置柱子的宽度
itemStyle: {
normal:{ //通常情况下:
//设置柱子颜色,每个柱子的颜色即为colorList数组里的每一项,
//如果柱子数目多于colorList的长度,则柱子颜色循环使用该数组
color: function (params){
var colorList = ['rgb(164,205,238)','rgb(180,205,205)','rgb(251, 118, 123)','rgb(255,228,181)',
'rgb(255,140,0)','rgb(210,105,30)','rgb(255,127,80)'
];
return colorList[params.dataIndex];
},
label: {
show: true, //开启显示,
position: 'top', //设置数值在上方显示
textStyle: { //数值样式
color: 'black',
fontSize: 16
}
}
},
//鼠标悬停时:
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
},
}],
grid: {//控制边距
left: '10%',
right:'4%',
top:'50',
bottom : '20px',
containLabel: true,
},
};
myChart.setOption(option, true);//多次调用时option选项默认是合并(merge)的,加上true表示不合并配置
}
}
});
}
</script>
</body>
</html>
4.后端的数据格式如图
注意:后端我用的框架是spring boot,只要数据格式是这种就可以动态显示柱状图的数据。