将2d数组从ruby传递给javascript

时间:2013-04-16 22:14:36

标签: javascript ruby-on-rails ruby arrays

我想将一个2D数组从ruby传递给javascript。

我目前在视图中有这个ID:

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable(<%= @statistics %>);

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

        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>

@statistics是来自控制器的二维阵列

1 个答案:

答案 0 :(得分:3)

您要查找的方法是#to_json

var data = google.visualization.arrayToDataTable(<%= @statistics.to_json %>);

例如:

[["abc", 123], ["def", 456]].to_json # => [["abc",123],["def",456]]
[[1, 2], [3, 4], [5, 6]].to_json # => [[1,2],[3,4],[5,6]]

如果您的@statistics变量不是纯二维数组,则在将其输出为JSON之前可能需要进行额外处理。