我正在尝试将php文件创建的json数据解析为另一个脚本,并将其值显示为高图。
我创建json数据的data.php是这样的:
<?php
header("Content-type: application/json");
$dbhost = "localhost";
$dbuser = "db";
$dbpass = "xxxxx";
$dbname = "db";
$db = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname,$db);
$query = "SELECT * FROM monitor_total";
$result = mysql_query($query,$db);
while($row = mysql_fetch_array($result)) {
$date = $row["date"];
$count = $row["count"];
$array[] = array("date" =>$date,"count"=>$count);
}
echo json_encode($array);
?>
data.php输出为:
[{"date":"2012-11-23","count":"582311"},{"date":"2012-11-24","count":"582322"},{"date":"2012-11-22","count":"582121"},{"date":"2012-11-21","count":"581321"},{"date":"2012-11-19","count":"572821"},{"date":"2012-11-20","count":"581321"},{"date":"2012-11-18","count":"582421"},{"date":"2012-11-17","count":"579321"},{"date":"2012-11-16","count":"581321"},{"date":"2012-11-25","count":"558178"}]
在<script>
内:
var monitor_graph; // globally available
monitor_graph = new Highcharts.Chart({
chart: {
renderTo: 'graph',
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Registered and total players by date'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Players'
}
},
series: [{
name: 'Total Players',
data: []
}]
});
function requestData() {
$.ajax({
url: 'data.php',
success: function(data) {
$.each(data, function(i,item){
monitor_graph.series[0].setData(??????????);
});
setTimeout(requestData, 1000);
},
});
}
我如何创建一个名为总玩家的系列,其中x轴为'item.date',y轴为'item.count'
请帮助我!
更新: 我在每个内容中添加:
monitor_graph.xAxis[0].setCategories([item.date]);
monitor_graph.series[0].setData([parseFloat(item.count)]);
然后我现在完全按照我的需要得到1分,但出现以下错误:
Unexpected value NaN parsing y attribute.
答案 0 :(得分:2)
您需要将成功回调修改为此类
var categories=[];
var seriesData=[];
$.each(data,function(){
categories.push(this.date);
seriesData.push(parseInt(this.count));
});
chart.xAxis[0].setCategories(categories);
chart.series[0].setData(seriesData);
Series.setData()
方法需要一个int / float数组而不是字符串,应该使用整个数据集而不是每个点调用。你在$.each
里面这样做应该在这个循环之外完成。类别
<强> Demo @ jsFiddle 强>
答案 1 :(得分:1)
您收到的数据是带有对象的数组形式。您需要遍历数组,您已经在$ .each函数中执行了该操作。这将使您以i变量的形式访问每个对象。此变量可以通过点表示法访问所需的属性。在你的情况下,将是i.date和i.count。
据我所知,setData方法接受一个数组来表示你可以设置的值,所以替换你的????以下内容:
monitor_graph.series[0].setData([i.date, i.count]);
希望有所帮助。