最近刚开始做图形操作,纠结了一上午,highchat 动态绑定数据这块一直不知道怎么绑定,后来多次尝试,发现
1.x轴的数据是个数组格式,我从后台传到前台的时候,js中用数组进行处理数据,然后赋值到chat就不会报错,
2.y轴的数据和x轴数据还不一样,通过数组处理后发现还是无法显示。后来我在后台将数据添加了中括号[]括起来后,传到前台,然后前台在用eval()处理后就能够显示了
3.eval具有计算的功能,刚开始x轴的时候我用了eval对时间进行操作发现时间都是相减了,格式为:2017-07-27,格式居然为1998这样的。
下面是我的后台和前台的程序逻辑:
1.后台MVC控制器
1 public ActionResult Index() 2 { 3 return View(); 4 } 5 public ActionResult GetAllReport() 6 { 7 var result = new { key = "2017-01-02,2017-01-02,2017-01-02,2017-01-02,2017-01-02,2017-01-02,2017-01-02,2017-01-02,2017-01-02,2017-01-02,2017-01-02,2017-01-02", value1 = "[9,23,24,54,67,1,23,45,23,444,55,89]", value2 = "[99,89,78,67,76,75,49,47,21,32,33,55]" }; 8 return Json(result); 9 }
2.前台:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta c />
<title>Index</title>
<script src="~/charts/highcharts/exporting.js"></script>
<script src="~/charts/highcharts/highcharts.js"></script>
<script src="~/charts/highcharts/highcharts_jquery-1.8.3.min.js"></script>
</head>
<body>
<div>
</div>
</body>
</html>
<script type="text/javascript">
$(function () {
$.ajax({
url: '/Home/GetAllReport',
dataType: "json",
type: "POST",
data: null,
success: function (data) {
alert(data.key);
Chart(data.key, data.value1, data.value2);
}, error: function (jqXHR, textStatus, errorThrown) {
alert("出错");
}
});
});
function Chart(key, value1, value2) {
var mycars = new Array();
var myvalue1 = new Array();
var myvalue2 = new Array();
var _tkey = key.split(',');
for (var i = 0; i < _tkey.length; i++) {
mycars[i] = _tkey[i];
}
var _tvalue1 = value1.split(',');
for (var i = 0; i < _tvalue1.length; i++) {
myvalue1[i] = _tvalue1[i];
}
var _tvalue2 = value2.split(',');
for (var i = 0; i < _tvalue2.length; i++) {
myvalue2[i] = _tvalue2[i];
}
var chart = new Highcharts.Chart('container', {
title: {
text: '不同城市的月平均气温',
x: -20
},
subtitle: {
text: '数据来源: WorldClimate.com',
x: -20
},
xAxis: {
categories: mycars
},
yAxis: {
title: {
text: '温度 (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: '东京',
data: eval(value1)
}, {
name: '纽约',
data: eval(value2)
}]
});
}
</script>
另外呢还有一些 小处理
1. 2条折线重复的时候,鼠标放上去需要都显示数据
tooltip: { shared: true }
2. 去除highchat.com 网址
credits: { enabled: false }
3. 刷新数据的时候 需要将上次的折线图清除
function clearTable() { var series = chart.series; if (series.length > 0) { series[0].remove(false); } }