7

I am trying to pass a ruby array to a js view (js.erb format) but it doesn't work at all.

var array = "<%= @publishers_list %>";

The variable array is just set as a string with 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}]

I tried to pass a simple array like:

[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.

4

3 回答 3

12
var array = <%= escape_javascript @publisher_list.to_json %>
于 2013-04-25T09:13:58.203 回答
2

尝试这个:

var array = <%= j @publishers_list.to_json %>

j是简写escape_javascript(感谢评论者 lfx_cool)。

请参阅文档:http ://api.rubyonrails.org/classes/ERB/Util.html

要稍微清理一下你的视图代码,你也可以在你的控制器中@publishers_list变成。json这样,在您看来,您可以使用:

var array = <%= j @publishers_list %>
于 2013-04-25T09:14:13.663 回答
0

只需在 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 文件,例如:rails_action.js.erb

现在使用您的代码

var array = [];
array = "<%= @publishers_list %>";

谢谢。

于 2013-04-25T09:57:55.587 回答