`
单一色调
  • 浏览: 83992 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

SSH+Highcharts 异步加载图表 ——在思考中解决问题(二)

阅读更多

之前曾写过一篇关于动态加载highcharts的文章

SSH+Highcharts 生成动态图表 ——在思考中解决问题

现在出现了几个问题:

1、之前的加载方式是先发送ajax请求给后台action,通过返回的data来构建图表,那么如果页面上有一个按钮的话要重新构建图表数据,是不是又要把一样的代码重新再写一遍呢?

这样太麻烦,也太不合理了。

那么继续查询highcharts API,发现在方法中有如下一个方法:

redraw ()
Since 1.2.0

Redraw the chart after changes have been done to the data or axis extremes. All methods for updating axes, series or points have a parameter for redrawing the chart. This is true by default. But in many cases you want to do more than one operation on the chart before redrawing, for example add a number of points. In those cases it is a waste of resources to redraw the chart for each new point added. So you add the points and call chart.redraw() after.
Returns    null

 

显而易见,这就应该是重构图表的方法,后面肯定需要用到这个方法。

 

2、找到了重构图表的方法,那么如何把值赋予图表呢?

通过继续查找api,发现Series中有一个setData方法,点进demo,发现有如下一个实例:

 $('#button').click(function() {
        var chart = $('#container').highcharts();
        chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );
    });

 通过chart.series[0].setData 可以给图表赋值,那么接下来问题就简单了。现贴上关键代码:

 

$(function() {
var adsChart;
adsChart = new Highcharts.Chart({
//......
series : [{name:'新用户'},{name:'老用户'},{name:'下载量'},{name:'安装量'}]
});
//给图表加载值
var url = '${pageContext.request.contextPath}/chartAction!getAdsChart.action';
$.post(url, function(response) {
	newList = response.newList;
	oldList = response.oldList;
	downList = response.downList;
	installList = response.installList;

	adsChart.series[0].setData(newList);
	adsChart.series[1].setData(oldList);  
	adsChart.series[2].setData(downList);
	adsChart.series[3].setData(installList);
}, "json");
});

 楼主这里有4条折线,所以构建4个series。

 

3、通过ajax方式这样可以初始化图表,那么点击按钮的时候如何刷新图表呢?

动态构建图表的地方不需要变,还是需要这样setData。

之前我们都是在按钮是给其添加onclick事件,然后调用函数,但是在这个地方好像不管用,fiebug会提示adsChart is undefined ,那么应该如何调用?

需要在$(function(){})内部中给按钮注册点击事件:

$('#btnAdsCharts').on('click',function(e){
adsChart.showLoading();
	var month = $('#MonthCombo').combobox('getValue');
	var url = '${pageContext.request.contextPath}/chartAction!getAdsChart.action';
	var data = {
		month : month
	};
	$.post(url, data, function(response) {
		newList = response.newList;
		oldList = response.oldList;
		downList = response.downList;
		installList = response.installList;

		adsChart.series[0].setData(newList);
		adsChart.series[1].setData(oldList);  
		adsChart.series[2].setData(downList);
		adsChart.series[3].setData(installList);
		adsChart.hideLoading();
                //重构图表
		adsChart.redraw();
	}, "json");
})

 

至此大功告成。

效果如图所示:

 

  • 大小: 27.1 KB
2
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics