1. 程式人生 > >highcharts動態載入json資料

highcharts動態載入json資料

首先建立一個container
<body>

	<script src="js/highcharts.js"></script>
	<script src="js/exporting.js"></script>
	<div id="container"
		style="min-width:800px; height: 400px; margin: 0 auto"></div>



</body>

js函式

$(function() {
	var x = [];//X軸
	var y = [];//Y軸
	var xtext = [];//X軸TEXT
	var color = [ "gray", "pink", "blue", "yellow", "green", "#fff" ];
	$.ajax({
		type : 'get',
		url : "dept/getChartsJson.shtml",//請求資料的地址
		success : function(data) {
			//var json = eval("(" + data + ")");
			var json = eval("(" + data + ")");

			for ( var key in json.list) {
				json.list[key].y = json.list[key].count; //給Y軸賦值
				xtext = json.list[key].name;//給X軸TEXT賦值
				json.list[key].color = color[key];
			}
			chart.series[0].setData(json.list);//資料填充到highcharts上面
		},
		error : function(e) {
		}
	});

	var chart = new Highcharts.Chart({
		chart : {
			renderTo : 'container',
			type : 'column'
		},
		title : {
			text : '部門統計柱狀圖'
		},
		subtitle : {
			text : ''
		},
		xAxis : {

			categories : xtext
		},
		yAxis : {
			min : 0,
			title : {
				text : '人數 (個)'
			},
			labels : {//格式化縱座標的顯示風格  
				formatter : function() {
					return this.value;
				}
			},
			opposite : false
		//反轉  
		},
		legend : {//是否顯示底注  
			enabled : true
		},
		tooltip : {
			shared : true,
			useHTML : true
		},
		plotOptions : {
			series : {
				cursor : 'pointer',
				events : {
					click : function(e) {
						var value=e.point.id;
						location.href ="user/showTable.shtml?id=" +value;
					}
				}
			},
			column : {
				pointPadding : 0.2,
				borderWidth : 0
			}
		},
		series : [ {
			name : "人數"
		} ]

	});

});
後臺action
@RequestMapping(value="/getChartsJson" ,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getJson() {
		/*
		JSONObject params = new JSONObject();
		params.put("name", deptService.getDeptname());
		params.put("count", userService.getDeptCountList());
		*/
		List<Integer> listcount=userService.getDeptCountList();
		List<String> listname=deptService.getDeptname();
		List<Integer> listdeptid=deptService.getDeptid();
		
		JSONArray jsonarray=new JSONArray();
		for(int i=0;i<listcount.size();i++){
			JSONObject params = new JSONObject();
			params.put("name", listname.get(i));
			params.put("count", listcount.get(i) );
			params.put("id", listdeptid.get(i) );
			
			jsonarray.add(i,params );
		}
		JSONObject json = new JSONObject();
		json.put("list", jsonarray);
		String s=json.toString();
		return s;

	}
	
頁面顯示結果