admin管理员组

文章数量:1203823

I have a Ruby array like this in my controller:

 @location_list = [
        ['Mushrooms', 3],
        ['Onions', 1],
        ['Olives', 1], 
        ['Zucchini', 1],
        ['Pepperoni', 2]
      ]

And I am catching it like this in my view:

location_list = "<%= @location_list.to_json %>";

But if I do alert(location_list), I get:

[[&quot;Mushrooms&quot;,3],[&quot;Onions&quot;,1],[&quot;Olives&quot;,1],[&quot;Zucchini&quot;,1],[&quot;Pepperoni&quot;,2]]

How do I get the correspondent object without those &quot?

I have a Ruby array like this in my controller:

 @location_list = [
        ['Mushrooms', 3],
        ['Onions', 1],
        ['Olives', 1], 
        ['Zucchini', 1],
        ['Pepperoni', 2]
      ]

And I am catching it like this in my view:

location_list = "<%= @location_list.to_json %>";

But if I do alert(location_list), I get:

[[&quot;Mushrooms&quot;,3],[&quot;Onions&quot;,1],[&quot;Olives&quot;,1],[&quot;Zucchini&quot;,1],[&quot;Pepperoni&quot;,2]]

How do I get the correspondent object without those &quot?

Share Improve this question asked Jun 6, 2012 at 22:48 Hommer SmithHommer Smith 27.9k62 gold badges175 silver badges307 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 27

Try:

<%= raw @location_list.as_json %>

Using to_json will end up rendering a string, with embedded double-quotes, and would need to be JS-escaped. And it would be a string, not an array.

This worked for me:

<%= @location_list.to_s.gsub(''', '') %>

Basically use .to_s to convert the whole array to a string, then use .gsub(''','') to remove the quotes by replacing them with nothing.

本文标签: javascriptFrom Ruby array to JS array in Rails 39quote39Stack Overflow