我想使用 json 将 mysql 结果加载到 highcharts 的折线图中。在下面的代码中,xAxix 是手动进给的。我如何从 mysql 数据库动态提供它?您还会找到 php 代码和 html 代码。 谢谢
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("data.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: json
});
});
});
});
</script>
</body>
</html>
<?php
$con = mysqli_connect("localhost","root","","bdd");
if (!$con) {
die('Could not connect: ' . mysqli__connect_error());
}
//mysqli_select_db($con,"bdd");
$query="SELECT revenue FROM projections_sample";
$sth = mysqli_query($con,$query);
$rows = array();
$rows['name'] = 'Revenue';
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['revenue'];
}
$query2="SELECT overhead FROM projections_sample";
$sth = mysqli_query($con,$query2);
$rows1 = array();
$rows1['name'] = 'Overhead';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['overhead'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_free_result($sth);
mysqli_close($con);
?>
最佳答案
您只需将 JSON 代码回显
到图表设置的 xAxis 属性即可:
subtitle: {
text: '',
x: -20
},
xAxis: <?php echo json_encode($result, JSON_NUMERIC_CHECK); ?>,
yAxis: ...
或者,如果您使用 AJAX 请求检索数据,请在初始化图表之前执行该请求,并以相同的方式使用返回数据。
关于javascript - 如何动态输入 highchart 折线图的 xAxis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43524254/