0

我一直在使用 Google Analytics API 来获取一些与我的 GA 帐户相关的 JSON 数据,我想使用 Google Visualization API 在饼图上绘制这些数据。但是,我在使用动态数据填充饼图时遇到了问题,如果我使用文本字符串,则会出现错误“给 addRows 的参数必须是数字或数组”

使用 addRows() 方法,如果我使用变量 'd' 的输出而不是变量本身,则图表呈现良好,但图表似乎直接从变量读取数组时出现问题。有没有人让它动态工作?

到目前为止,这是我的代码:

<div id="chart_div" style="width: 900px; height: 500px;"></div>

var list = [];
var j = "";
var d = "";

$(window).load(function(){  
    var myjson = 'my json response data';
    // my json already fetched from the server using ASP.NET

    j = $.parseJSON(myjson);

    $.each(j.rows, function() {
       list.push("['" + this[0].toString() + "'," + this[7] + "]");
    }); 
    // I push all JSON entries from the 'rows' object into an array, 
    // but choose only the 1st and 8th column for the relevant data
    // and format it to be readable by the Google Visualization API 

    d = "[" + list + "]";
});


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

function drawChart() {
    var data = new google.visualization.DataTable();     

    data.addColumn('string', 'Label');
    data.addColumn('number', 'Value');

    data.addRows(d);

    var options = {
        title: 'My Daily Activities'
    };

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

1 回答 1

0

For anyone interested in the answer - I got this working by following this answer on another thread, using the eval() method. Swapping "data.addRows(d);" for "data.addRows(eval(d));" did the trick.

于 2013-06-14T13:34:25.413 回答