2013-11-04 164 views
0

我無法正確顯示Google圖表。我試圖用Ajax和PHP來做到這一點。Google圖表無法正確顯示值

這是在頁面上加載代碼:

<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> 

,並在charts_ajax.php文件中,有這樣的數據:

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

    $arrTableData = $_GET['d']; 

    echo json_encode($arrTableData); 
} 
?> 

這就是下圖是輸出:

GoogleChart Output

有沒有人可以對此進行說明,po可以幫我修好嗎?

+0

在您的'$ .getJSON'調用的回調函數中,添加以下行:console.dir(data);',在Chrome或Firefox中打開頁面,並查看開發者的控制檯。應該有一行輸出數據的內容。它看起來像什麼,它是一個字符串還是一個javascript數組(如果它是一個javascript數組的JSON字符串表示形式,這是一個重要的區別)? – asgallant

回答

0

您是否試過將數據轉換爲Google Charts JSON格式?這是一個例子。

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\": ["; 
     }