ruby 数组到 javascript - Rails
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16210798/
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
ruby array to javascript - Rails
提问by Mencls
I am trying to pass a ruby array to a js view (js.erbformat) but it doesn't work at all.
我正在尝试将 ruby 数组传递给 js 视图(js.erb格式),但它根本不起作用。
var array = "<%= @publishers_list %>";
var array = "<%= @publishers_list %>";
The variable arrayis just set as a stringwith all the array's values in it.
变量数组只是设置为一个字符串,其中包含所有数组的值。
Is there a way to keep the array format ?
有没有办法保持数组格式?
Edit
编辑
I just realized it was because of my array format.
我刚刚意识到这是因为我的数组格式。
[{:label => "name1", :value => value1}, {:label => "name2", :value => value2}]
[{:label => "name1", :value => value1}, {:label => "name2", :value => value2}]
I tried to pass a simple array like:
我试图传递一个简单的数组,如:
[1,2,3]
[1,2,3]
and it worked fine.
它工作正常。
The question is now: how can I pass this kind of array ? I really need to keep these hashes in it because I want to put it as a source of a jQuery autocomplete.
现在的问题是:如何传递这种数组?我真的需要在其中保留这些哈希值,因为我想将其作为 jQuery 自动完成的来源。
回答by manoj
var array = <%= escape_javascript @publisher_list.to_json %>
回答by Christian-G
Try this:
试试这个:
var array = <%= j @publishers_list.to_json %>
j
is shorthand for escape_javascript
(thanks to commenter lfx_cool).
j
是escape_javascript
(感谢评论者 lfx_cool)的简写。
See the documentation: http://api.rubyonrails.org/classes/ERB/Util.html
请参阅文档:http: //api.rubyonrails.org/classes/ERB/Util.html
To clean up your view code a little, you can also turn the @publishers_list
into json
in your controller. That way, in your view you can just use:
为了稍微清理你的视图代码,你也可以在你的控制器中@publishers_list
转换成json
。这样,在您看来,您只需使用:
var array = <%= j @publishers_list %>
回答by rony36
simply define a array in Controller's specific action like:
只需在 Controller 的特定操作中定义一个数组,例如:
def rails_action
@publishers_list = []
# write some code to insert value inside this array
# like:
# @publishers.each do |publisher|
# @publishers_list << publisher.name
# end
end
js file which is associated with this action, like: rails_action.js.erb
与此操作关联的 js 文件,例如:rails_action.js.erb
now use your code
现在使用你的代码
var array = [];
array = "<%= @publishers_list %>";
Thanks.
谢谢。