刚入门菜鸟一只
搞了一个晚上-------(:
需求: 使用Ajax请求后台,后台传回json的map,前台解析传给highcharts制作饼图
优点: 使用Map不用新建类, 前台解析灵活性强,饼分的个数不会受限制(根据后台的数据来分)
后台代码如下:
package com.xdl.web.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xdl.dao.DatabaseInfDao;
@Controller
public class GetVideoInfController {
//请求地址
@RequestMapping("/getVideoInfByBig_type.do")
//返回值为json
@ResponseBody
public List<Map<String, Integer>> getVideoInfByBig_type(){
//创建容器
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取Dao层
DatabaseInfDao dif = ac.getBean("databaseInfDao",DatabaseInfDao.class);
//获取数据
List<Map<String, Object>> bigtype_idAll = dif.getBigtype_idAll();
List<Map<String, Integer>> list=new ArrayList<>();
for(Map<String, Object> map1:bigtype_idAll){
Integer count = dif.getVideoInfByBig_type((int)map1.get("id"));
Map<String, Integer> map=new HashMap<>();
map.put((String)map1.get("name"), count);
list.add(map);
}
//得到list集合返回
System.out.println(list);//list中的数据库中获取的[{前端开发=668}, {后端开发=939}, {移动开发=375}, {数据库=506}, {UI设计=513}]
return list;
}
}
前端jsp代码:
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',//设置词饼图在哪显示
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
}
}
},
series: [{
type: 'pie',
name: '份额'
}]
});
});
$.ajax({
url:"getVideoInfByBig_type.do",
dataType:"json",
cache: true,
type: "POST",
data:null,
async: true,
success:function(data){
//定义一个数组
maps = [],
//循环迭代
$.each(data,function(i,d){
//d为一个map对象
for(var key in d){
//向maps中添加数据
maps.push([key,d[key]]);
}
alert(maps);
});
//设置饼图中的数据(这一步很关键)
chart.series[0].setData(maps);
},
error:function(){
alert("error");
}
});
});
</script>
<!-- 这是显示饼图的区域 --> <div id="container" style="min-width:700px;height:400px"></div>