将2d数组从ruby传递给javascript

时间:2022-08-27 07:53:00

I want to pass a 2d array from ruby to javascript.

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

I currently have this id in the view:

我目前在视图中有这个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 is a 2d array comin from the controller

@statistics是来自控制器的2d阵列

1 个解决方案

#1


3  

The method you are looking for is #to_json.

您正在寻找的方法是#to_json。

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

For example:

例如:

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

If your @statistics variable is not a plain 2D array, it may require additional processing before you output it to JSON.

如果您的@statistics变量不是普通的2D数组,则在将其输出到JSON之前可能需要进行额外的处理。

#1


3  

The method you are looking for is #to_json.

您正在寻找的方法是#to_json。

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

For example:

例如:

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

If your @statistics variable is not a plain 2D array, it may require additional processing before you output it to JSON.

如果您的@statistics变量不是普通的2D数组,则在将其输出到JSON之前可能需要进行额外的处理。