直接看代码
<script language="JavaScript"> $(document).ready(function() { $.ajax({ type:‘post‘, url:‘<%=basePath%>charts/getData?type=column‘, success:function(result){ result=eval(result); var chart={ type:‘column‘ } var title = { text: ‘班级统计‘ }; var xAxis = { categories: [‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘five‘] }; var yAxis = { title: { text: ‘比例‘ } }; var plotOptions = { line: { dataLabels: { enabled: true }, enableMouseTracking: true } }; var series= result; var credits = { enabled: false }; var json = {}; json.chart=chart; json.title = title; json.xAxis = xAxis; json.yAxis = yAxis; json.series = series; json.credits = credits; json.plotOptions = plotOptions; $(‘#container‘).highcharts(json); }, error:function(){ alert(2); } }); }); </script>
后台代码:
@RequestMapping(value="getData",method=RequestMethod.POST) public void getData(HttpServletRequest request,HttpServletResponse response,String type){ List list = new ArrayList(); HighCharts hc = new HighCharts(); HighCharts hc2 = new HighCharts(); List lt = new ArrayList(); List lt2 = new ArrayList(); hc.setName("test"); hc2.setName("wolf"); hc.setType("line"); hc2.setType("line"); Random rd=new Random(); for (int i=0;i<10;i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "test1"); map.put("y", rd.nextInt(100)); map.put("percentage", (i+1)*0.3*100); lt.add(map); } for (int i=0;i<10;i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "test1"); map.put("y", rd.nextInt(100)); map.put("percentage", (i+1)*0.3*100); lt2.add(map); } hc.setData(lt); hc2.setData(lt2); list.add(JSONObject.toJSON(hc)); list.add(JSONObject.toJSON(hc2)); try { response.getWriter().print(list); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
效果图:
再后台代码中如果设置
hc.setType("column");
hc2.setType("column");
则展示的是直方图:
当然也可以改为pie,显示饼状图,但因为饼状图只适合显示单个数组的情况,结果两个会重合,因此饼状图是最简单的图表。
注意:在后台代码中如果不设置type,则默认为line,此时,js中的chart中的type生效,所以type生效的顺序是数据中的type(后台代码,也是series)>js中chart的type。
例如:在后台设置
hc.setType("column");
hc2.setType("column");
然后在js的chart中设置
chart={
type:‘line‘
}
结果仍为柱状图:
时间: 2024-11-10 01:16:58