2

我正在尝试使用 .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

如何解决这个问题?

4

2 回答 2

3

试试这个从文件中获取 json 数据。

var data = $.ajax({
                 url: "Data",
                 dataType: "json",
                 async: false,
                 }).responseText;
于 2013-02-21T10:42:15.250 回答
2
// 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);
    });
}
于 2013-02-19T08:03:00.827 回答