1

我有以下生成 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]]);

有用。

你能帮我理解我错在哪里吗?

谢谢!

4

1 回答 1

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));
于 2013-10-08T12:44:29.370 回答