我正在尝试完成一个关于从MySQL获取JSON字符串并将其准备用于highcharts的教程,但它不起作用,我不知道为什么。。。。
HTML:
<script type="text/javascript" src="js/jquery.min.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>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
JSON字符串是使用文件生成的
data.php:
<?php
$con = mysql_connect("*****", "*****", "*****");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*****", $con);
$sth = mysql_query("SELECT revenue FROM projections_sample");
$rows = array();
$rows['name'] = 'Revenue';
while ($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['revenue'];
}
$sth = mysql_query("SELECT overhead FROM projections_sample");
$rows1 = array();
$rows1['name'] = 'Overhead';
while ($rr = mysql_fetch_assoc($sth)) {
$rows1['data'][] = $rr['overhead'];
}
$result = array();
array_push($result, $rows);
array_push($result, $rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
如果我手动将JSON字符串输入data.php,图表将按预期显示。
[{
"name": "Revenue",
"data": [23987, 24784, 25899, 25569, 25897, 25668, 24114, 23899, 24987, 25111, 25899, 23221]
}, {
"name": "Overhead",
"data": [21990, 22365, 21987, 22369, 22558, 22987, 23521, 23003, 22756, 23112, 22987, 22897]
}]
我假设我的连接细节是正确的,因为如果我故意输入错误的密码,我会得到MySQL连接错误。。。
“Could not connect: Access denied for user ‘*****’@'localhost’ (using password: YES)”
此外,当我将“echo @mysql_ping() ? ‘true’ : ‘false’;”
添加到页面底部时,会返回“True”
。
因为我确信它应该可以工作,我想知道是否有任何与服务器配置相关的东西可以阻止我使用JSON?
如果不能使用JSON_NUMERIC_CHECK
(因为它需要PHP 5.3.3(json.常量))
可以转换为int
[$number = (int)"1234";
]
在中
while ($r = mysql_fetch_array($sth)) {
$rows['data'][] = (int)$r['revenue']; // <- (int)
}
和
while ($rr = mysql_fetch_assoc($sth)) {
$rows1['data'][] = (int)$rr['overhead']; // <- (int)
}
比
print json_encode($result);