我有一个.js.erb模板,我正在做:
var foo = <%= [1,2,3] %>; var foo2 = <%= [1,3].to_json %>; var foo3 = <%= ["bar"].to_json %>; var foo4 = <%= {:foo => "bar"}.to_json %>;
foo等于123
foo2等于[1,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
我无法以这种方式工作……我试着这样做:
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 ecapes html实体!
解决方案是:
var foo =<%= {:lol => [“lmaonade”,“rotflcopter”]}.to_json.html_safe}%>
这给了我:
{"lol": ["lmaonade","rotflcopter"]}