Pass Rails JSON variable to javascript variable

我怕爱的太早我们不能终老 提交于 2019-12-22 03:22:26

问题


I have a Global JSON variable in my Ruby on Rails controller. It looks like this @rails_side_json = { :name => 'Will', :age => 23 }.to_json

I want this to be assigned to my javascript variable (var javascript_side_json) which resides in my javascript file named custom.js.erb

The value in javascript_side_json variable after the assignment is done should be equivalent to me writing var javascript_side_json = {"name": "Will", "age": 23 };

I am not able to achieve this by writing var javascript_side_json = <%= @rails_side_json %>

How can I achieve this? Do I need to make changes in multiple files?


回答1:


You are almost done. Just need to make sure your json is safe html:

var javascript_side_json = <%= @rails_side_json.html_safe %>;

or

var javascript_side_json = <%=raw @rails_side_json %>;



回答2:


The JSON will be escaped by default. You can tell the view to use in the code using raw

var javascript_side_json = <%= raw @rails_side_json %>


来源:https://stackoverflow.com/questions/22421501/pass-rails-json-variable-to-javascript-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!