Highcharts 是一款非常漂亮兼容 IE6+、完美支持移动端、图表类型丰富、方便快捷的 HTML5 交互性图表库。不过官方的示例只有静态的演示。
Highcharts 官方演示地址:https://www.hcharts.cn/demo/highcharts
那么如何通过ajax异步获取后台数据并绑定到 Highcharts 图表中? 这里我以基础折线图为示例,其他类型的图表也是一样的。
#####前端html代码
```
Document$(function () {
//页面初始加载数据
$.get("users.php", '', function (data) {
columnBasic(data.date, data.user);
});
//column-basic
function columnBasic(categories, series) {
$('#container').highcharts({
chart: {
type: 'line',
backgroundColor: null,
color: '#ffffff'
},
title: {
text: '用户数七天变化'
},
subtitle: {
text: ' '
},
xAxis: {
categories: categories,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: '人数 (个)'
}
},
plotOptions: {
line: {
dataLabels: {
// 开启数据标签
enabled: true
},
// 关闭鼠标跟踪,对应的提示框、点击事件会失效
enableMouseTracking: false
}
},
series: [{
name: '用户',
data: eval("[" + series + "]")
}]
});
}
});
```
#####PHP后台代码
```
public function users()
{
// 指定返回格式为 JSON
header("Content-type: text/json");
//获取最近七天日期
$dates = get_weeks();
//$date为一维数组['10-24','10-25', ....]
$user = [];
$date = [];
foreach ($dates as $k=>$w){
$user[] = Db::name('member')->whereBetweenTime('last_login_time', $w)->count();
$date[] = substr($w, 5);
}
return json([
'date' => $date,
'user' => $user
]);
}
```
到此就已经实现了ajax异步获取后台数据并绑定到 highcharts 图表中。希望可以帮助到大家。