Rails: pass data to javascript -


i'm new in rails , in controller have:

class pagescontroller < applicationcontroller    def home       @temp = "hello"    end end 

i have read must put javascript code in application.js (tell me if true) , have:

window.onload=function(){alert("<%= j @temp %>")} 

obviously alert print string "<%= j @temp %>" how can pass variable @temp javascript alert can print hello?

thanks

i wrote article on how pass ruby objects client. ryan bates has excellent railscast on passing data js.

add div view corresponds pagescontrolle#home action not visible when load page contain data stored in ruby objects:

# views/pages_controllers/home.html.erb <%= content_tag :div, class: "temp_information", data: {temp: @temp} %> <% end %> 

load page div included , view page source. can see ruby objects stored in .temp_information div. open javascript console access ruby objects javascript objects:

$('.temp_information').data('temp') 

you not need add js js partial, can use asset pipeline.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -