ECharts使用Ajax动态载入图表数据

jsp代码:(根据官方demo及自己需求,适当修改原始参数,需动态添加的原始测试数据可以不删,可以覆盖)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


<html>
<head>
<meta charset="UTF-8">
<title>Insert title heretitle>
  
  <script src="<%=request.getContextPath() %>/vendor/jquery.min.js">script>
  
  <script src="<%=request.getContextPath() %>/vendor/echarts.js">script>
head>
<body>

    
    <div id="main" style="width: 800px;height:600px;">div>
    <script type="text/javascript">
 
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('main'));

        // 指定图表的配置项和数据
        var option = {
        				title: {
        			        text: '堆叠区域图'
        			    },
        			    tooltip : {
        			        trigger: 'axis',
        			        axisPointer: {
        			            type: 'cross',
        			            label: {
        			                backgroundColor: '#6a7985'
        			            }
        			        }
        			    },
        			    legend: {
        			    //data为需动态添加的数据,原始测试数据可删可不删
        			        data:['邮件营销','联盟广告','视频广告','直接访问','搜索引擎']
        			    },
        			    toolbox: {
        			        feature: {
        			            saveAsImage: {}
        			        }
        			    },
        			    grid: {
        			        left: '3%',
        			        right: '4%',
        			        bottom: '3%',
        			        containLabel: true
        			    },
        			    xAxis : [
        			        {
        			            type : 'category',
        			            boundaryGap : false,
        			            //按需求手动设置了月份参数
        			            data : ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']
        			        }
        			    ],
        			    yAxis : [
        			        {
        			            type : 'value'
        			        }
        			    ],
        			    //series中数据为需动态添加的数据,原始测试数据可删可不删
        			    series : [
        			        {
        			            name:'邮件营销',
        			            type:'line',
        			            stack: '总量',
        			            areaStyle: {},
        			            data:[120, 132, 101, 134, 90, 230, 210, 0, 0, 0, 0, 0]
        			        },
        			        {
        			            name:'联盟广告',
        			            type:'line',
        			            stack: '总量',
        			            areaStyle: {},
        			            data:[220, 182, 191, 234, 290, 330, 310, 100, 110, 110, 110, 110]
        			        },
        			        {
        			            name:'视频广告',
        			            type:'line',
        			            stack: '总量',
        			            areaStyle: {},
        			            data:[150, 232, 201, 154, 190, 330, 410, 20, 20, 20, 20, 20]
        			        },
        			        {
        			            name:'直接访问',
        			            type:'line',
        			            stack: '总量',
        			            areaStyle: {normal: {}},
        			            data:[320, 332, 301, 334, 390, 330, 320, 60, 60, 60, 60, 60]
        			        },
        			        {
        			            name:'搜索引擎',
        			            type:'line',
        			            stack: '总量',
        			            label: {
        			                normal: {
        			                    show: true,
        			                    position: 'top'
        			                }
        			            },
        			            areaStyle: {normal: {}},
        			            data:[820, 932, 901, 934, 1290, 1330, 1320, 1000, 1000, 1000, 1000, 1000]
        			        }
        			    ]
        		
        			};
      
        	var url = '<%=request.getContextPath()%>/consume/photoServlet?method=photo';
         	$.post(url,function(jsonData){  
         		//更新数据			
	     		option.legend.data=jsonData[0];
	     		option.series=jsonData[1];   			
	     		myChart.hideLoading();  
	     		// 更新显示图表。
	     		myChart.setOption(option);
         	},'json');     	
    script>
body>
html>

后台srevlet:

package com.consume.bhy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.consume.bhy.service.PhotoService;

@WebServlet(urlPatterns="/consume/photoServlet")
public class PhotoServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Class<?> class1 = this.getClass();	
		String methodName = request.getParameter("method");
		
		try {
			Method method = class1.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			method.setAccessible(true);
			try {
				method.invoke(this, request,response);
				
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}
			
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		
	}

	public void photo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/palin;charset=utf-8");
		
		//创建一个JSON数组存放返回的数据
		JSONArray jsonData = new JSONArray();
		
        PhotoService ps = new PhotoService();
        jsonData = ps.getJsonData();
 
        //获取输出流写数据
        PrintWriter writer = response.getWriter();
        writer.print(jsonData);
		
	}
	
}

后台service:

package com.consume.bhy.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.consume.bhy.jdbc.JDBC_Util;

public class PhotoService {
	public JSONArray getJsonData() throws SQLException {
		//创建数组存放legend中date数据
		JSONArray legendData = new JSONArray();
		//创建数组存放series的数据
		JSONArray series = new JSONArray();
		//连接操作数据库,查询数据
		Connection conn = JDBC_Util.getConnection();
		String sql = "select consume_type_id,consume_type_name from consume_type";
		PreparedStatement prepared = conn.prepareStatement(sql);
		ResultSet resultSet = prepared.executeQuery();
		while(resultSet.next()) {
			String sql2 = "select month(consume_date) m, SUM(consume_price*consume_count) s from consume_info where consume_type_id=? group by month(consume_date) ORDER BY month(consume_date);";
			PreparedStatement prepared2 = conn.prepareStatement(sql2);
			prepared2.setInt(1, resultSet.getInt("consume_type_id"));
			ResultSet resultSet2 = prepared2.executeQuery();
			double[] consumedate =new double[12];
			while(resultSet2.next()) {
				consumedate[resultSet2.getInt("m")-1]= resultSet2.getBigDecimal("s").doubleValue();
			}
			JDBC_Util.clossJDBC(prepared2, resultSet2);
			JSONObject serie = new JSONObject();
			
			//将每种消费类型相应的参数存入serie对象并按顺序存入series数组
			serie.put("name", resultSet.getString("consume_type_name"));
		    serie.put("type", "line");
		    serie.put("stack", "总量");
		    serie.put("areaStyle", new JSONObject());
		    serie.put("data", consumedate);
			
		    series.add(serie);
		    //将消费类型顺序存入legendData
			legendData.add(resultSet.getString("consume_type_name"));
		}
		//最后添加月总消费到legendData
		legendData.add("月总消费");
		JDBC_Util.clossJDBC(prepared, resultSet);
		String sql3 = "select month(consume_date) m, SUM(consume_price*consume_count) s from consume_info group by month(consume_date) ORDER BY month(consume_date);";
		PreparedStatement prepared3 = conn.prepareStatement(sql3);
		ResultSet resultSet3 = prepared3.executeQuery();
		double[] allConsume =new double[12];
		while(resultSet3.next()) {
			allConsume[resultSet3.getInt("m")-1]= resultSet3.getBigDecimal("s").doubleValue();
		}
		JDBC_Util.clossJDBC(conn, prepared3, resultSet3);
		
		JSONObject allSerie = new JSONObject();
		
		allSerie.put("name", "月总消费");
		allSerie.put("type", "line");
		allSerie.put("stack", "总量");
		allSerie.put("areaStyle", new JSONObject());
		allSerie.put("data", allConsume);
		//将月总消费的相应的参数存入allSerie对象并存入series数组
	    series.add(allSerie);

	    //创建jsonData数组保存legendData和series数组并返回
		JSONArray jsonData = new JSONArray();
		jsonData.add(legendData);
		jsonData.add(series);

		return jsonData;
	}

}

效果图:ECharts使用Ajax动态载入图表数据_第1张图片

你可能感兴趣的:(图形化插件,功能开发,前端框架)