本文介绍了如何使用.js.erb将ruby数据结构转换为javascript数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.js.erb模板,我正在做:

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等于123


foo equals 123

foo2等于[1,2,3]

foo2 equals [1,2,3]

foo3未定义(因为浏览器抱怨解析错误)

foo3 is undefined (because the browser complains of a parse error)

foo4未定义(因为浏览器抱怨解析错误)

foo4 is undefined (because the browser complains of a parse error)

只有这样我才能弄明白如何让foo3工作:

The only way I could figure out how to get foo3 to work was to do:

var foo3 = "<%= ['bar'].to_json %>";    # foo3 => "[&quot;bar&quot;]"
foo3.replace(/&quot;/g, "\""))          # => "['bar']"  <-- looks like eval should work...
eval(foo3.replace(/&quot;/g, "\""))[0]; # => "bar" ... it works

我无法以这种方式工作......我尝试过:

I could not foo4 to work in this way... I tried doing:

var foo4 = <%= "{:foo => 'bar'}.to_json" %>;  # foo4 => "{&quot;foo:&quot;:&quot;bar&quot;}" %>;
foo4.replace(/&quot;/g, "\""));               # => "{"foo":"bar"}"  <-- looks like eval should work
eval(foo4.replace(/&quot;/g, "\""));           # => "Parse error"   <-- but it doesn't...

底线,这一切需要使用eval的东西是荒谬的 - 必须有一个更好的方法!有人可以告诉我它是什么吗?!?!

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?!?!

推荐答案

问题是.to_json ecapes html实体!

The problem was .to_json ecapes the html entities!

解决方案是:

var foo =<%= {:lol => [lmaonade ,rotflcopter]}。to_json.html_safe}%>

var foo = <%= {:lol => ["lmaonade", "rotflcopter"]}.to_json.html_safe } %>

这给了我:

{"lol": ["lmaonade", "rotflcopter"]}

这篇关于如何使用.js.erb将ruby数据结构转换为javascript数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:44