将 Rails JSON 变量传递给 javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22421501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass Rails JSON variable to javascript variable
提问by user3422637
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
我的 Ruby on Rails 控制器中有一个全局 JSON 变量。看起来像这样@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
我希望将其分配给我的 javascript 变量(var javascript_side_json),该变量位于我名为 custom.js.erb 的 javascript 文件中
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 };
赋值完成后 javascript_side_json 变量中的值应该相当于我写 var javascript_side_json = {"name": "Will", "age": 23 };
I am not able to achieve this by writing var javascript_side_json = <%= @rails_side_json %>
我无法通过编写var javascript_side_json = <%= @rails_side_json %>来实现这一点
How can I achieve this? Do I need to make changes in multiple files?
我怎样才能做到这一点?我需要在多个文件中进行更改吗?
回答by Muntasim
You are almost done. Just need to make sure your json is safe html:
你快完成了。只需要确保您的 json 是安全的 html:
var javascript_side_json = <%= @rails_side_json.html_safe %>;
or
或者
var javascript_side_json = <%=raw @rails_side_json %>;
回答by Zero Fiber
The JSON will be escaped by default. You can tell the view to use in the code using raw
默认情况下将转义 JSON。您可以告诉视图在代码中使用raw
var javascript_side_json = <%= raw @rails_side_json %>