将字符串传递给Google Chart addRows

时间:2013-10-08 10:27:16

标签: javascript google-visualization google-chartwrapper

我有以下生成Google图表的功能,但它不起作用:

function drawChart(a) {
          alert(a.test);
          var data = new google.visualization.DataTable();       
          data.addColumn('string', 'Year');
          data.addColumn('number', 'Sales');
          data.addColumn('number', 'Expenses');
          data.addRows(a.test);


          var options = {
                             title: 'Company Performance'
                         };

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

“a.test”检索以下字符串:

test="[['2004', 1000, 400],['2005', 1170, 460],['2006', 660, 1120],['2007', 1030, 540]]";

但如果我以这种方式直接放置值

data.addRows([['2004', 1000, 400],['2005', 1170, 460],['2006', 660, 1120],['2007', 1030, 540]]);

它有效。

请你帮我理解错误的地方?

谢谢!

1 个答案:

答案 0 :(得分:4)

addRows方法接受数组数组,而不是字符串,因此您需要将a.test更改为数组或将其更改为JSON字符串并在其上调用JSON.parse

// note that the internal quotes are double-quotes here, as that is required by JSON
var foo = '[["2004", 1000, 400],["2005", 1170, 460],["2006", 660, 1120],["2007", 1030, 540]]';
data.addRows(JSON.parse(foo));