1. 程式人生 > >百度圖表ECharts的非同步載入

百度圖表ECharts的非同步載入

最近要用圖表,所以去使用了下echarts,不過在非同步載入的過程中一直無法顯示,後來發現其實是個很坑的問題,因為之前做開發的時候一直都是ctrl + c,ctrl + v,導致自己都忘了在載入json的時候需要在方法的後面加上json引數!!

jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String ctx = request.getContextPath();
	request.setAttribute("ctx", ctx);
%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
		<script src="${ctx}/statics/js/jquery-1.12.4.min.js"></script>
		<script src="${ctx}/statics/js/echarts.js"></script>
	</head>
	<body>
		<div id="mainCharts" style="width: 600px;height:400px;"></div>
		<script>
		
			var myChart = echarts.init(document.getElementById('mainCharts'));
			// 顯示標題,圖例和空的座標軸
			myChart.setOption({
			    title: {
			        text: '非同步資料載入示例'
			    },
			    tooltip: {},
			    legend: {
			        data:['銷量']
			    },
			    xAxis: {
			        data: []
			    },
			    yAxis: {},
			    series: [{
			        name: '銷量',
			        type: 'bar',
			        data: []
			    }]
			});
			// 非同步載入資料
			myChart.showLoading();
			$.get('${ctx}/ChartsServlet?method=test1',function (data) {
				myChart.hideLoading();
			    // 填入資料
			    myChart.setOption({
			        xAxis: {
			            data: data.categories
			        },
			        series: [{
			            // 根據名字對應到相應的系列
			            name: '銷量',
			            data: data.data
			        }]
			    });
			}, 'json');
		</script>
	</body>
</html>
java:
package com.liberty.echarts;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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.JSONObject;

@WebServlet("/ChartsServlet")
public class ChartsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String method = request.getParameter("method");
		if("test1".equals(method)) {
			test1(request, response);
		}
	}
	
	private void test1(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> data = new HashMap<>();
		String[] cateArr = new String[]{"襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"};
		data.put("categories", cateArr);
		int[] dataArr = new int[]{5, 20, 36, 10, 10, 20};
		data.put("data", dataArr);
		response.getWriter().println(JSONObject.toJSON(data));
	}
}
裡面解析json使用的是alibaba的fastjson