简体   繁体   中英

How to pass a Javascript variable to Rails Controller?

Inside my index.html.erb

<script type= "text/javascript">
  var msg = "Hello World" ;
</script>

i need pass this var msg to my controller say get_variable() method in my Post controller.

Edit : get javascript variable msg in same index.html.erb as ruby variable Thanks in Advance

Try this

<%= link_to_remote, 'Message', :url=>{:controller=>'controller_name', :action=>'method_name'}, :with=> "'msg='+msg" %>

controller_name.rb

def method_name
  @message= params[:msg]
  puts @message # >> should be print "Hello World"

end

EDITED

<%= link_to_remote, 'Message', :url=>{:controller=>'controller_name', :action=>'method_name'}, :with=> "'msg='+msg" %>
<div id ='show_message'></div>

controller_name.rb

def method_name
  @message= params[:msg]
  render :update do|page|
    page.replace_html 'show_message', @message
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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