简体   繁体   中英

Escaping " in Rails and Javascript

I have an array of hashes that consists of my product data in @product_records. I can extract the name of the product using the map function like this:

<%= @product_records.map{|x|x["Name"]} %>

which renders exactly how I want it to the page like this:

["Product1","Product2",...,"Productn"]

I want to try and pass this into a javascript variable so that I can use it with JQuery autocomplete.

var data = <%= @product_records.map{|x|x["Name"]} %>

When I try and set it though the double quotes are escaping like this:

[&quot;Product1&quot;, &quot;Product2&quot;,...,&quot;Productn&quot;]

I have tried various things to try and get the quotes back (.to_json etc) but nothing seems to work. There probably a very simple answer to this but I can't find what it is.

Cheers for any help.

使用<%= raw your_variable %> :)

When you use that variable in javascript make sure, you have single quote to execute rails code in javascript.

'<%= raw @products.to_json %>'

thanks

在我的情况下,我不得不这样使用,例如: <%= j raw @products %>

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