通过AJAX / JSON的Highcharts饼图:但是切片错误和Json格式不正确?

时间:2011-11-28 00:13:35

标签: php ajax json highcharts

我是新手php / js / mysql程序员。

我正在尝试使用jquery在highcharts中创建一个饼图,其中数据是通过php中的echo json_encode的ajax动态发现的(包括来自mysql的select查询)。

两个问题:

1)饼图上到处都有这些尾随的“Slice:0%”耀斑。不知道这些来自何处,意味着什么,也不知道如何解决它。

2)Json对我来说是新手。 json数据源似乎正在通过(firebug看到它),但格式如下所示。我正试图将其归结为名称和百分比数字。像这样['Pages',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);
?>

1 个答案:

答案 0 :(得分:0)

第一个问题,如何将数据转换为highcharts要接受的格式(即数组数组,[[name,percent],[nextname,percent]等])?我会在你的PHP中处理这个:

<snip>

// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());

$total = 0;
$results = array(); 

while ( $row = mysql_fetch_assoc( $result )) { 
  $results[$row["contenttype"] = $row["count()"];
  $total +=  $row["count()"];
}

$forHigh = array();
foreach ($results as $k => $v) {
    $forHigh[]=array($k,($v/$total) * 100); // get percent and push onto array
}

echo json_encode($forHigh); // this should be an array of array

既然我们的JSON返回结构已经为HighCharts做好了准备,我们只需要在JSON调用之后调用一次创建绘图来创建绘图。我会在$ .ajax调用的成功回调中做到这一点。

$.ajax({
    url: 'hc1.php', 
    success: function(jsonData) {
        chart = new Highcharts.Chart({
        <snip>
                series: [{
                  type: 'pie',
                  name: 'Content',
                  data: jsonData
                }]
        <snip>
    },
    cache: false
});