2013-05-25 56 views
0

我嘗試解析一個JSON基於本指南中的PHP文件結構數據:谷歌圖表JSON裝載雙引號

https://google-developers.appspot.com/chart/interactive/docs/php_example?hl=en

我已經創建了我的JSON的一個好辦法,但是當我用這個代碼它似乎不讀取JSON得好:

function drawChart() { 
    var jsonData = $.ajax({ 
     url: "loader.php", 
     dataType:"json", 
     async: false 
     }).responseText; 

我認爲這是因爲在this example JavaScript對象沒有引號一些麻煩的JSON的鍵雙引號。那麼我應該錯過什麼地方?

我的腳本代碼:

<script type="text/javascript"> 

     // Load the Visualization API and the piechart package. 
     google.load('visualization', '1.0', {'packages':['corechart']}); 

     // Set a callback to run when the Google Visualization API is loaded. 
     google.setOnLoadCallback(drawChart); 


     function drawChart() { 

     var jsonData = $.ajax({ 
       dataType:"json", 
       url: "loader.php", 
       async: false 
       }).responseText; 

     // Create our data table out of JSON data loaded from server. 
     var data = new google.visualization.DataTable(jsonData); 



     // Instantiate and draw our chart, passing in some options. 
     var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 
     chart.draw(data, {title: 'Results', width: 400, height: 240}); 

    } 
    </script> 

和我loader.php回報是什麼的源代碼:

{"cols": 
    [{"label":"Sources","type":"string"}, 
    {"label":"Count","type":"number"}], 
"rows": 
    [{"c":[{"v":"web"},{"v":"4757"}]}, 
    {"c":[{"v":" iPhone"},{"v":"4324"}]}, 
    {"c":[{"v":"Android"},{"v":"3294"}]}, 
    {"c":[{"v":"BlackBerry\u00ae"},{"v":"2336"}]}, 
    {"c":[{"v":"Instagram"},{"v":"951"}]} 
    ]} 

注:圖表負荷良好,沒有錯誤,但不加載JSON。它說:其他100%。所以標籤和行都不是正確的。

+1

你確定它不會加載該JSON ?這些數字實際上並不是數字,因此Google無法顯示餅圖(因爲沒有可顯示的值)。代碼運行後顯示的內容是什麼? 'alert(data.getValue(1,1))'的警報是什麼? – jmac

回答

0

這些值不能被引用。刪除引號,例如

var jsonData={"cols": 
    [{"label":"Sources","type":"string"}, 
    {"label":"Count","type":"number"}], 
"rows": 
    [{"c":[{"v":"web"},{"v":4757}]}, 
    {"c":[{"v":" iPhone"},{"v":4324}]}, 
    {"c":[{"v":"Android"},{"v":3294}]}, 
    {"c":[{"v":"BlackBerry"},{"v":2336}]}, 
    {"c":[{"v":"Instagram"},{"v":951}]} 
    ]}; 

圖表正在工作。

NB:要知道黑莓\ u00ae轉移的,你有你的loader.php一些解碼/編碼的問題(但不是問題的根源)