ECharts使用Ajax動態載入圖表數據

jsp代碼:(根據官方demo及自己需求,適當修改原始參數,需動態添加的原始測試數據可以不刪,可以覆蓋)

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

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

    <!-- 爲ECharts準備一個具備大小(寬高)的Dom -->
    <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;
	}

}

效果圖:在這裏插入圖片描述


歡迎訪問本文的個人博客鏈接: https://br-bai.github.io/2018/10/18/ECharts使用Ajax動態載入圖表數據/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章