javascript - Iterate through a hash from the Rails controller in js -


in rails controller have made hash looks this:

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

now want iterate in js through hash keys , values. @ first need term tried like:

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

but seems did wrong it's first time use rails..

passing data server side ruby controller client side javascript code not simple. firstly, javascript has no idea ruby variables, above string '#{data}' evaluates itself.

there couple of ways of passing such data:

firstly, can set html attribute on dom element server side , read in javascript. might simplest solution when passing string or number, hash quite messy need convert form understandable javascipt - json. though simple do, adds complexity , dirty.

second option gon gem. provides object can assign data in controller. handles transformations , can access data in javascript:

# controller gon.my_data = {a: 1}  #js gon.mydata  #=> {"a": 1} 

this solution simple, still feels little bit dirty.

final, cleanest , more complex solution use ajax - javascript makes request server receive data. might overkill in many situation.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -