简体   繁体   English

通过js中的Rails控制器遍历哈希

[英]Iterate through a hash from the Rails controller in js

In my rails controller i have made an hash which looks like this: 在我的rails控制器中,我做了一个哈希,看起来像这样:

@data = {

 term => {        
   node_id => {
    :name,
    :matchcode,
    :credits,
    :parts => [{
      :mp_id,
      :matchcode,
      :nr,
      :selected
    }]

}}

Now i want to iterate in js through this hash to get the keys and values. 现在,我想通过此哈希在js中进行迭代以获取键和值。 At first I need the term i tried to get it with something like: 首先,我需要一个术语,我试图用类似的东西来理解它:

for(var s in '#{@data}') {
   console.log(s);
}

But i seems like I did something wrong it's the first time i use rails.. 但是我好像做错了什么,这是我第一次使用rails ..

Passing data from the server side ruby controller to client side javascript code is not that simple. 从服务器端红宝石控制器向客户端javascript代码传递数据并不是那么简单。 Firstly, javascript has no idea about ruby variables, the above is simply string '#{data}' which evaluates to itself. 首先,javascript不了解ruby变量,上面只是字符串'#{data}'对其进行求值。

There are couple of ways of passing such a data: 有两种传递此类数据的方法:

Firstly, you can set an html attribute on DOM element server side and then read it in your javascript. 首先,您可以在DOM元素服务器端设置html属性,然后在javascript中读取它。 This might be simplest solution when passing a string or a number, for a hash however it is quite messy as you need to convert it into a form understandable by javascipt - into JSON. 这对于传递字符串或数字而言,对于散列而言可能是最简单的解决方案,但是它很杂乱,因为您需要将其转换为javascipt可以理解的形式-转换为JSON。 Even though it is very simple to do, it just adds extra complexity and is just dirty. 即使这样做很简单,也只会增加额外的复杂性,而且很脏。

Second option is a gon gem. 第二个选择是gon宝石。 It provides you with an object you can assign data to in your controller. 它为您提供了一个对象,您可以在控制器中分配数据。 Then it handles all the transformations and you can access all the data in your javascript: 然后,它处理所有转换,您可以访问javascript中的所有数据:

# controller
gon.my_data = {a: 1}

#js
gon.myData  #=> {"a": 1}

This solution is very simple, however it still feels a little bit dirty. 该解决方案非常简单,但是仍然有点脏。

Final, cleanest and more complex solution is to use AJAX - your javascript makes a request to your server to receive the data. 最终,最简洁,更复杂的解决方案是使用AJAX-您的JavaScript向服务器发出请求以接收数据。 Might be an overkill in many situation. 在许多情况下可能是过大的杀伤力。

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

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