我是一個新手php/js/mysql程序員。通過AJAX/JSON的Highcharts餅圖:但切片錯誤和Json格式不正確?
我想創建一個使用jquery的highcharts中的餅圖,其中的數據是通過ajax從php中的echo json_encode動態發現的(包括mysql的select查詢)。
兩個問題:
1)餅圖具有這些尾隨 「切片:0%」 無處不耀斑。不知道這些來自哪裏,它的意思,也不知道如何解決。
2)Json對我來說是新的。 JSON數據饋送似乎正在通過(螢火蟲看到它),但格式看起來像這樣。我試圖把它歸結爲名稱和百分比數字。像這樣['頁',45.0]但不知道如何。這是在json/php中完成,還是應該在sql查詢本身完成?
[{"contenttype":"BLOGPOST","count(*)":"2076"},{"contenttype":"COMMENT","count(*)":"2054"},{"contenttype":"MAIL","count(*)":"29448"},{"contenttype":"PAGE","count(*)":"33819"}]
任何幫助非常讚賞
的highcharts js文件是在這裏:
//Define the chart variable globally,
var chart;
//Request data from the server, add it to the graph and set a timeout to request again
function requestData() {
$.ajax({
url: 'hc1.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function(){
//Create the test chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'mycontainer2',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
events: {load: requestData}
},
title: {text: 'Content Types in Wiki'},
tooltip: {formatter: function() {return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
//color: Highcharts.theme.textColor || '#000000',
//connectorColor: Highcharts.theme.textColor || '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Content',
data: []
}]
});
PHP文件是在這裏:
<?php
// Set the JSON header
header("Content-type: text/json");
// Connect to db
include('dbconnect.php');
// Count version 1 of content types of interest
$query = ("select contenttype, count(*)
from CONTENT
where version='1' and contenttype='page' or contenttype='comment' or contenttype='blogpost' or contenttype='mail' or contenttype='drafts'
group by CONTENT.contenttype;");
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// create a php array and echo it as json
//$row = mysql_fetch_assoc($result);
//echo json_encode($row);
$results = array(); while ($row = mysql_fetch_assoc($result)) { $results[] = $row; }
echo json_encode($results);
?>
我對你的代碼有點困惑。它每秒鐘都會向劇情添加一個新的數據點。這對餅圖來說會是一件奇怪的事情?你的意思是每秒重繪一次餅圖(又似乎是奇怪的)?或者你只是想繪製一次圖表? – Mark
嗨馬克。只需畫一次。 – gregm
這裏是柱狀圖的例子可以幫助你。 http://sgeek.org/create-chart-using-mysql-highcharts/ –