简体   繁体   中英

From Ruby array to JS array in Rails- 'quote'?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM