首先先看下图片
前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- 引入 layui.css --> <link rel="stylesheet" href="layui/css/layui.css"> <!-- 引入 layui.js --> <script src="layui/layui.js"></script> <!-- 引入 echarts.js --> <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <div> <form class="layui-form" action="" onsubmit="return false"> <div class="layui-inline"> <label class="layui-form-label">请输入年份</label> <div class="layui-input-inline"> <input type="text" name="year" class="layui-input"> </div> </div> <div class="layui-inline"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="formSearch">搜索</button> </div> </div> </form> </div> <!-- 为ECharts准备一个具备大小(宽高)的Dom --> <div id="main" style=" 600px;height:400px;align-content: center"></div> <script type="text/javascript"> // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); layui.use(['util', 'layer', 'table', 'form', 'jquery', 'laydate'], function () { var util = layui.util , layer = layui.layer , table = layui.table , $ = layui.jquery , laydate = layui.laydate , form = layui.form; //搜索一下 form.on('submit(formSearch)', function (data) { // layer.msg(JSON.stringify(data.field)); console.log(data.field.year); $.ajax({ url: '/VisitServlet', type: 'GET', data: { 'year': data.field.year, }, success: function (res) { console.log(res.data); var list = res.data; //发生 改变 图标 myChart.setOption({ series: [ { name: res.name, type: res.type, // 设置图表类型为饼图 radius: '55%', // 饼图的半径,外半径为可视区尺寸(容器高宽中较小一项)的 55% 长度。 data: (function () { var res = []; for (var i = 1; i <= 12; i++) { res.push({ //通过把result进行遍历循环来获取数据并放入Echarts中 name: i + "月", value: list[i] }); } return res; })() } ] }); }, dataType: 'json' }); }); }); </script> </body> </html>
思考:
参考菜鸟教程实例,主要是data怎样遍历,上面是定义了res数组,将数据push到数组中并返回
参考博客:https://blog.csdn.net/m0_37116405/article/details/55095929