rea*_*123 29 javascript ruby json ruby-on-rails
我正试图从我的控制器获取我的JSON到我的视图.在我的控制器中我正在做:
@nodes = Node.all
@json = @nodes.as_json(:only => [:ID, :Lat, :Lon])
Run Code Online (Sandbox Code Playgroud)
在我看来,我尝试过:
1) var stuff = <%= @json %>
2) var stuff = <%= @json.to_json %>
3) var stuff = <%= @json.to_json.to_json %>
Run Code Online (Sandbox Code Playgroud)
所有这些都给了我一个错误.我经常得到一个"Unexpected Syntax Error &" or "Unexpected Syntax Error {"
我也尝试过使用jquery并在控制器中使用respond_to,但这似乎也不起作用.
我的想法是让json访问视图应该不是一个大问题,不应该需要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
Run Code Online (Sandbox Code Playgroud)
我不理解符号(可能是语法错误的来源),但是当我执行渲染:时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}}
Run Code Online (Sandbox Code Playgroud)
注意:我也尝试过做var stuff = '<%= @json.to_json
%>但是当我这样做时var json = JSON.parse(stuff)
,它会给我一个非法的令牌错误.
有人可以帮我这个吗?非常感谢!
Laa*_*aas 55
这是Rails html编码你的字符串,这是Rails 3中的默认值.
您需要将JSON标记为html_safe
:
var stuff = <%= @json.to_s.html_safe %>
Run Code Online (Sandbox Code Playgroud)
请注意,这.to_s
是必需的,因为as_json
提供Hash而不是字符串.你可以这样做:
# in controller
@json = @nodes.to_json(:only => [:ID, :Lat, :Lon])
#and in view
var stuff = <%= @json.html_safe %>
Run Code Online (Sandbox Code Playgroud)