【发布时间】:2014-05-08 09:51:07
【问题描述】:
我尝试使用 JSON 数据制作高图表。我制作了一个生成 json 的 php 文件,并将地址插入到 getJSON() 中。
$(document).ready(function() {
$.getJSON("data.php", function(json) {
chart = new Highcharts.Chart({
chart: {...
它不起作用,所以我决定像这样将 php 放入 highcharts 文件中。
<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$resu = array();
$measurement = $_POST["choosenmeasurement"];
for($i = 0; $i < count($_POST["choosenbusid"]); $i++)
{
$busid = $_POST["choosenbusid"][$i];
$clusid = $_POST["choosenclusterid"][$i];
$fieldname = ''.$measurement.'_BUSID_'.$busid.'_CLUSTERID_'.$clusid;
$sql= "SELECT unix_timestamp, $measurement as $fieldname FROM `get` WHERE bus_id = $busid and cluster_id = $clusid";
$sth = $mysqli->query($sql);
$out = array();
$out['name'] = $fieldname;
while ($rr = $sth->fetch_assoc()) {
$out['data'][] = $rr[$fieldname];
}
array_push($resu,$out);
}
$jsonresult = json_encode($resu);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON(<?php $jsonresult>, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'testchart',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
yAxis: {
title: {
text: ''
},
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="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
它也不会加载,我尝试了很多方法,比如将 $jsonresult 放入 javascript 变量,回显 json,打印 json,打印/回显到 getJSON() 中,即使我回显仍然无法工作将 json 放到一个空白处,它会打印出我想要的 json 结构。
但是
如果我像这样将 JSON 文件放入 getJSON() 中
$(document).ready(function() {
$.getJSON("test.json", function(json)
它会起作用的。但我不会在每次加载图表时将生成的 json 复制粘贴到 json 文件中。
我只是想知道为什么。有什么帮助吗?
【问题讨论】:
-
第一个猜测是生成的 JSON 不正确。我建议验证您在服务器上生成的 JSON(您可以使用它:jsonlint.com)。无论如何,您在 JavaScript 控制台中有什么错误?
-
一件事,你可以运行 echo $jsonresult 来查看它的格式并将其包含在你的帖子中。
-
我试过了。这是一个 valod json
-
[{"name":"Hz_BUSID_1_CLUSTERID_1","data":["49.5798","49.58","49.58","49.58","49.58","49.58","49.58" ]},{"name":"Hz_BUSID_2_CLUSTERID_1","data":["49.5798","49.58","49.58","49.58","49.58","49.58","49.58"]},{"name ":"Hz_BUSID_1_CLUSTERID_2","data":["48.4136","48.4137","48.4137","48.4137","48.4137","48.4137","48.4138"]},{"name":"Hz_BUSID_6_CLUSTERID_1", "数据":["49.5798","49.58","49.58","49.58","49.58","49.58","49.58"]}]
-
你的值是字符串,应该是数字。
标签: javascript php json highcharts