简体   繁体   English

Google图表无法正确显示值

[英]Google Charts not displaying values correctly

I'm having trouble displaying Google Charts correctly. 我无法正确显示Google图表。 I'm trying to do this with Ajax and PHP. 我正在尝试使用Ajax和PHP。

This is the code that is loaded on the page: 这是页面上加载的代码:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type='text/javascript'>

    // Dummy Array for now
    <?php
        $php_array = array(
        array('Terms', 'Visits'),
        array('test', 25),
        array('joke', 25),
        array('funny', 50),
    );

    //Convert the PHP Array into a Javascript Array
    $js_array = json_encode($php_array);
    echo "var arrTableData = ". $js_array . ";\n";
    ?>

    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawCharts);

    function drawCharts(){

        // Each chart function

        $.getJSON('charts_ajax.php',{'a' : 'terms', 'd'  : arrTableData }, function(data){

            if(data){

                initGoogleChart(data)

            }else {
                console.log("There is no data coming back");
            }
        });


    }
    function initGoogleChart(data){

        var tableData = google.visualization.arrayToDataTable(data);

        var options = {
            title: 'Title'
        };

        var chart = new google.visualization.PieChart(document.getElementById('terms-table'));
        chart.draw(tableData, options);
    }
</script>

and on the charts_ajax.php file there is this data: 在Charts_ajax.php文件上有以下数据:

<?php
if ($_GET['a'] == "terms") {

    $arrTableData = $_GET['d'];

    echo json_encode($arrTableData);
}
?>

This is what the Chart is outputting: 这是图表输出的内容:

GoogleChart输出

Can anybody shed some light on this and possible help me fix it please? 谁能对此有所启发,请帮助我解决这个问题?

Have you tried converting the data into a Google Charts JSON format? 您是否尝试过将数据转换为Google Charts JSON格式? Here's an example. 这是一个例子。

    foreach($arrTableData as $r2) {
        if(!isset($google_JSON2)) {    
            $google_JSON2 = "{\"cols\": [";
            $column = array_keys($r2);

            foreach($column as $key=>$value) {
                $google_JSON_cols2[]="{\"id\": ".$key.", \"label\": \"".$value."\", \"type\": \"string\"}";
            }    

            $google_JSON2 .= implode(",",$google_JSON_cols2)."],\"rows\": [";
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM