Echarts 获取后台数据 使用后台数据展示 柱形图

后台数据要以json格式返回

页面:引用echarts.js , 然后data以ajax的数据请求并返回

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>ECharts</title>
</head>

<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="height:400px"></div>
<script src="http://echarts.baidu.com/build/dist/echarts.js"></script>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

});
// 路径配置
require.config({
paths: {
echarts: 'http://echarts.baidu.com/build/dist'
}
});
// 使用
require(
[
'echarts',
'echarts/chart/bar' // 使用柱状图就加载bar模块,按需加载
],
function (ec) {
// 基于准备好的dom,初始化echarts图表
var myChart = ec.init(document.getElementById('main'));
var option = {
tooltip: {
show: true
},
title: {
text: ''
},
legend: {
data:["姓名"]
},
xAxis : [
{
type : "category",
data : (function(){
var arr=[];
$.ajax({
type : "post",
async : false, //同步执行
url : "<%=basePath%>getUserJson",
data : {},
dataType : "json", //返回数据形式为json
success : function(result) {
if (result) {
for(var i=0;i<result.length;i++){
console.log(result[i].userName);
arr.push(result[i].userName);
}
console.log("arr=>"+arr);
}

},
error : function(errorMsg) {
alert("获取图表请求数据失败!");
myChart.hideLoading();
}
})
return arr;
})()
}
],
yAxis : [
{
type : "value"
}
],
series : [
{
"name":"年龄",
"type":"bar",
"data":(function(){
var arr=[];
$.ajax({
type : "post",
async : false, //同步执行
url : "<%=basePath%>getUserJson",
data : {},
dataType : "json", //返回数据形式为json
success : function(result) {
if (result) {
for(var i=0;i<result.length;i++){
console.log(result[i].age);
arr.push(result[i].age);
}
}
},
error : function(errorMsg) {
alert("获取图表请求数据失败!");
myChart.hideLoading();
}
})
return arr;
})()

}
]
};
// 为echarts对象加载数据
myChart.setOption(option);
}
);
</script>
</body>

============================================================

原文地址:https://www.cnblogs.com/austinspark-jessylu/p/6292672.html