简体   繁体   English

如何将Rails数据上的ruby数据输入d3.js?

[英]How can I feed ruby on rails data into d3.js?

I'm currently having trouble figuring out how to feed a hash that I created in ruby on rails into javascript code that I am using with d3.js to create a line graph to show numerical values over time. 我目前在弄清楚如何将在Rails中在ruby中创建的哈希值馈送到与d3.js一起使用的javascript代码中,以创建折线图来显示一段时间内的数值。

The hash is currently set up as { :date => value, :date => value, etc. } 当前将哈希设置为{:date => value,:date => value等。

I did .to_json to turn them into json but then I'm having a lot of trouble pulling these values in javascript to be the x and y values of my graph. 我做了.to_json将它们转换为json,但是在将这些值在javascript中作为我的图形的x和y值时遇到了很多麻烦。

Could anyone please help point me in the right direction? 有人可以帮我指出正确的方向吗?

Thanks! 谢谢!

There are different ways to do this ... you could do it with AJAX for example. 有多种方法可以执行此操作...例如,您可以使用AJAX进行此操作。

But here's a really simple way to do it: 但这是一种非常简单的方法:

<script>
  <% my_ruby_hash = { foo: "bar" } %>
  var jsonString = "<%= my_ruby_hash.to_json %>"
  var parsedData = JSON.parse(jsonString)
</script>

I have used the gon gem for generating similar graph with d3.js 我已经用gon gem与d3.js生成了类似的图形

In your gem file add gem gon 在您的gem文件中添加gem gon

gem 'gon'

in your relevant controller for example I use index 例如在您的相关控制器中,我使用索引

def index
  data = 'some data in what ever format you like'
  gon.data = data
end

in your view you can access gon data and pass it to relevant javascript function 在您看来,您可以访问gon数据并将其传递给相关的javascript函数

<script type="text/javascript" charset="utf-8">
  $( document ).ready(function() {
  var dataset = gon.data;
  plot_graph(dataset);
  });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM