我正在尝试将我的 JSON 从我的 Controller 获取到我的 View 。在我的 Controller 中我正在做:
@nodes = Node.all
@json = @nodes.as_json(:only => [:ID, :Lat, :Lon])
在我看来我已经尝试过:
1) var stuff = <%= @json %>
2) var stuff = <%= @json.to_json %>
3) var stuff = <%= @json.to_json.to_json %>
所有这些都给我一个错误。我通常会得到一个 "Unexpected Syntax Error &" or "Unexpected Syntax Error {"
我也尝试过在 Controller 中使用 jquery 和 respond_to,但这似乎也不起作用。
我的想法是让 json 进入 View 应该不是什么大问题,也不应该需要 jQuery,目前,我的页面源代码如下所示:
var stuff = [{"node":{"ID":1301499692582,"Lat":42.3605063113369,"Lon":-71.0870862191138}},{"node":{"ID":1301499691515,"Lat":42.3605147089149,"Lon":-71.0870533282532}},{"node":{"ID":1301431075499,"Lat":42.3605456103,"Lon":-71.0875239075536}} etc
我不理解 " 符号(也许这就是语法错误的来源)但是当我渲染时:json => @nodes.to_json
,页面会渲染一个有效的普通 json:
[{"node":{"ID":1301499692582,"Lat":42.3605063113369,"Lon":-71.0870862191138}},{"node":{"ID":1301499691515,"Lat":42.3605147089149,"Lon":-71.0870533282532}},{"node":{"ID":1301431075499,"Lat":42.3605456103,"Lon":-71.0875239075536}}
注意:我也试过做 var stuff = '<%= @json.to_json
%> 但是当我做 var json = JSON.parse(stuff)
时,它给了我一个非法 token 错误。
有人可以帮我解决这个问题吗?非常感谢!
最佳答案
这是 Rails 对您的字符串进行 html 编码的方式,这是 Rails 3 中的默认设置。
您需要将您的 JSON 标记为 html_safe
:
var stuff = <%= @json.to_s.html_safe %>
注意 .to_s
是必需的,因为 as_json
给出的是 Hash 而不是字符串。你可以这样做:
# in controller
@json = @nodes.to_json(:only => [:ID, :Lat, :Lon])
#and in view
var stuff = <%= @json.html_safe %>
https://stackoverflow.com/questions/5970419/