简体   繁体   中英

How to use a ruby hash as a options for javascript function

I have a hash in ruby which holds options which I want to input for a javascript function

my hash is (as it prints in irb)

@options = [{:source=>"2", :tries=>"3"}]

my javascript function accepts options like

myFunc({source: num, tries: num})

So if in a js.erb file I do

myFunc(<%=j @options %>)

It would result in

{:source=&gt;\&quot;2\&quot;, :tries=&gt;\&quot;3\&quot;}

doing j @edges.to_json results in

 \&quot;{:source=&gt;\\\&quot;2\\\&quot;, :target=&gt;\\\&quot;3\\\&quot;} }\&quot;

doing j @edges.to_json.html_safe results in

\"{:source=>\\\"2\\\", :target=>\\\"3\\\"}\"

Is there way to make it output a more javascript friendly hash?

dont use j . try

myFunc(<%= @options.to_json %>)

You may use gsub to remove those unwanted chars:

@options[0].to_json.gsub(/\"/,'')
# => "{source:2,tries:3}"

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