我有一个.js.erb模板,正在执行:
var foo = <%= [1,2,3] %>;
var foo2 = <%= [1,2,3].to_json %>;
var foo3 = <%= ["bar"].to_json %>;
var foo4 = <%= {:foo => "bar"}.to_json %>;
foo等于123
foo2等于[1,2,3]
foo3是未定义的(因为浏览器抱怨解析错误)
foo4是未定义的(因为浏览器抱怨解析错误)
我能弄清楚如何使foo3正常工作的唯一方法是:
var foo3 = "<%= ['bar'].to_json %>"; # foo3 => "["bar"]"
foo3.replace(/"/g, "\"")) # => "['bar']" <-- looks like eval should work...
eval(foo3.replace(/"/g, "\""))[0]; # => "bar" ... it works
我无法foo4以这种方式工作...我尝试这样做:
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...
最重要的是,所有需要使用eval的东西都是荒谬的-必须有更好的方法!有人可以告诉我这是什么吗?!?!
最佳答案
问题是.to_json使html实体转义!
解决方案是:
var foo = [“lmaonade”,“roflcopter”]}。to_json.html_safe}%>
这给了我:
{"lol": ["lmaonade", "rotflcopter"]}