Круговая диаграмма Highcharts через AJAX / JSON: а ошибки срезов и формат Json не верны? - PullRequest
0 голосов
/ 28 ноября 2011

Я новичок в программировании php / js / mysql.

Я пытаюсь создать круговую диаграмму в старших диаграммах, используя jquery, где данные обнаруживаются динамически через ajax из echo json_encode в php (включаетзапрос на выборку из mysql).

Две проблемы:

1) На круговой диаграмме повсюду вспыхивают следующие "ломтики: 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"}]

Любая помощь, высоко ценимая

Файл 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 голосов
/ 28 ноября 2011

Первая проблема, как вы переводите свои данные в формат, который будут принимать старшие диаграммы (а именно, массивы массивов, [[name, процент], [следующее имя, процент] и т. Д.])?Я бы обработал это в вашем 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
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...