如何将Ruby数组传递给Javascript以生成折线图

时间:2021-10-20 11:52:43

I am trying to make a webpage to display line graphs in my Ruby on Rails 2.3.14 application. I found a tool, called JS Charts, which allows me to create nice graphs using Javascript, but I am having trouble sending it the data it needs. Here is the way to make a static line graph:

我正在尝试创建一个网页,以在我的Ruby on Rails 2.3.14应用程序中显示折线图。我找到了一个名为JS Charts的工具,它允许我使用Javascript创建漂亮的图形,但是我无法向它发送所需的数据。以下是制作静态线图的方法:

<script type="text/javascript">
  var myData = new Array([1, 395], [2, 244], [3, 223], [4, 210], [5, 238], [6, 223], [7, 275], [8, 31]);
  var myChart = new JSChart('chartcontainer', 'line');
  myChart.setDataArray(myData);
  myChart.draw();
</script>

I put that code into stats.html.erb, and it shows up. However, I need it to display line graph data that I provide it. A 2 dimensional array is created in the controller:

我将该代码放入stats.html.erb中,然后显示出来。但是,我需要它来显示我提供的线图数据。在控制器中创建一个二维数组:

>> @a
=> [[1, 395], [2, 244], [3, 223], [4, 210], [5, 238], [6, 223], [7, 275], [8, 31]]

I should be able to use that variable in the view, and set var myData to it, with something like:

我应该能够在视图中使用该变量,并将var myData设置为它,例如:

var myData = "<%= @a %>";

I tried other things like:

我试过其他的事情:

var myData = JSON.parse( "<%= @a.to_json %>" );

but nothing seems to work. Is there anything I can do?

但似乎没什么用。有什么我可以做的吗?

EDIT:

编辑:

There was an issue with the array the controller passed into the view (@a), which was empty. I was able to use:

控制器传入视图(@a)的数组存在问题,该视图为空。我能够使用:

var myData = JSON.parse( "<%= @a.to_json %>" );

to display the line graph with the right data being passed into the view.

显示正确数据传递到视图中的折线图。

1 个解决方案

#1


8  

Seem's like you got it working but you can clean things up a bit:

看起来就像你让它工作但你可以稍微清理一下:

<%= javascript_tag do %>
  window.myData = <%=raw @a.to_json %>;
<% end %>

or in rails 3 you can be super HTML5 savy and use the data helpers to add your data as an att of some html tag:

或者在rails 3中你可以超级HTML5 savy并使用数据助手将你的数据添加为一些html标签的att:

<%= content_tag "div", id: "myDiv", data: {stuff: @a} do %>
<!-- some html stuff...-->
<% end %>

and then in then in the javascript (with jQuery):

然后在javascript中(使用jQuery):

var myData = $('#myDiv').data("stuff")

and for the super keen, check out this railscast

而且对于超级敏锐的人来说,看一下这个看门票

#1


8  

Seem's like you got it working but you can clean things up a bit:

看起来就像你让它工作但你可以稍微清理一下:

<%= javascript_tag do %>
  window.myData = <%=raw @a.to_json %>;
<% end %>

or in rails 3 you can be super HTML5 savy and use the data helpers to add your data as an att of some html tag:

或者在rails 3中你可以超级HTML5 savy并使用数据助手将你的数据添加为一些html标签的att:

<%= content_tag "div", id: "myDiv", data: {stuff: @a} do %>
<!-- some html stuff...-->
<% end %>

and then in then in the javascript (with jQuery):

然后在javascript中(使用jQuery):

var myData = $('#myDiv').data("stuff")

and for the super keen, check out this railscast

而且对于超级敏锐的人来说,看一下这个看门票