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

mod rewrite - Using "?" when rewriting the URL -

.htaccess: Transfer name to index.php if not directory public -

Admob integration with pygame in android -