I have a .js.erb template and I am doing:
var foo = <%= [1,2,3] %>;
var foo2 = <%= [1,2,3].to_json %>;
var foo3 = <%= ["bar"].to_json %>;
var foo4 = <%= {:foo => "bar"}.to_json %>;
foo equals 123
foo2 equals [1,2,3]
foo3 is undefined (because the browser complains of a parse error)
foo4 is undefined (because the browser complains of a parse error)
The only way I could figure out how to get foo3 to work was to do:
var foo3 = "<%= ['bar'].to_json %>"; # foo3 => "["bar"]"
foo3.replace(/"/g, "\"")) # => "['bar']" <-- looks like eval should work...
eval(foo3.replace(/"/g, "\""))[0]; # => "bar" ... it works
I could not foo4 to work in this way... I tried doing:
var foo4 = <%= "{:foo => 'bar'}.to_json" %>; # foo4 => "{"foo:":"bar"}" %>;
foo4.replace(/"/g, "\"")); # => "{"foo":"bar"}" <-- looks like eval should work
eval(foo4.replace(/"/g, "\"")); # => "Parse error" <-- but it doesn't...
Bottom line, all this needing to use eval stuff is ridiculous-- there MUST be a better way! Can someone please enlighten me as to what it is?!?!
The problem was .to_json ecapes the html entities!
The solution was to do:
var foo = <%= {:lol => ["lmaonade", "rotflcopter"]}.to_json.html_safe } %>
This gives me:
{"lol": ["lmaonade", "rotflcopter"]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With