2013-02-19 67 views
2

我想繪製使用谷歌圖表使用.json文件中的值線圖。我已經嘗試過但沒有成功。谷歌圖表:數據從.json文件

這是我以.json文件

[ 
    { 
     "Year":2005, 
     "Sales":25000, 
    }, 
    { 
     "Year":2006, 
     "Sales":25085, 
    }, 
    { 
     "Year":2007, 
     "Sales":186230, 
    }, 
    { 
     "Year":2008, 
     "Sales":35036, 
    }, 
    { 
     "Year":2009, 
     "Sales":15900, 
    }, 
    { 
     "Year":2010, 
     "Sales":35700, 
    } 
] 

代碼

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

    function loadData(fileName) { 
     // getting json from a remote file 
     // by returning the jqXHR object we can use the .done() function on it 
     // so the callback gets executed as soon as the request returns successfully 
     return $.getJSON(fileName + ".json"); 
    } 

    function drawChart() { 
      var myFile = "Data"; 

     var obj= loadData(myFile); 
     var data = google.visualization.arrayToDataTable(obj); 

     var options = { 
      title: 'Chart Demo' 
     }; 

     var chart = new google.visualization.LineChart(
        document.getElementById('chart_div')); 
     chart.draw(data, options); 
    } 

錯誤

Error: Not an array 
http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js 
Line 2 

如何解決這一問題?

+0

你能不能把'的console.log(數據);'行'後VAR數據= google.visualization.arrayToDataTable(OBJ);',看看你做了什麼...... – 2013-02-19 07:59:33

+0

@ Will.i .am在控制檯中仍然出現同樣的錯誤 – Okky 2013-02-19 08:03:33

+0

請注意,您聲明瞭一個永遠不會使用的名爲'dataTable'的變量。 – 2013-02-19 08:08:05

回答

3

試試這個從文件中獲取JSON數據。

var data = $.ajax({ 
       url: "Data", 
       dataType: "json", 
       async: false, 
       }).responseText; 
+0

這方面的一些更新工作。感謝名單 – Okky 2013-02-21 10:42:50

1
// by returning the jqXHR object we can use the .done() function on it 
// so the callback gets executed as soon as the request returns successfully 

您不使用.done(),所以當你通過obj你傳遞一個jqXHR對象,最有可能甚至還沒有獲取的數據。


這應該工作:

function drawChart() { 
    var myFile = "Data"; 

    //Use getJSON and process the file contents in the callback function 
    $.getJSON(myFile + '.json', function(obj) { 

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

     var options = { 
      title: 'Chart Demo' 
     }; 

     var chart = new google.visualization.LineChart(document.getElementById('chart_div')); 
     chart.draw(data, options); 
    }); 
} 
+0

我沒有收到任何錯誤。但該圖不顯示。 – Okky 2013-02-19 08:08:54

+0

由於我沒有與谷歌可視化工作,我無法幫助你。我只能指出錯誤的jQuery/JavaScript。 – 2013-02-19 16:15:59