Rails中奇怪的JSON Javascript问题 [英] Weird JSON Javascript problem in Rails
问题描述
我正在尝试从控制器获取JSON到视图.在我的控制器中,我正在做
I'm trying to get my JSON from my controller to my view. In my controller I am doing:
@nodes = Node.all
@json = @nodes.as_json(:only => [:ID, :Lat, :Lon])
在我看来,我已经尝试过:
In my view I have tried:
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 {"
and all of those give me an error. I usually get an "Unexpected Syntax Error &" or "Unexpected Syntax Error {"
我也尝试过在控制器中使用jquery并使用response_to,但这似乎也不起作用.
I have also tried using jquery and using respond_to within the controller, but that doesn't seem to work either.
我的想法是,将json放入视图应该不是一个大问题,也不需要jQuery,目前,我的页面源代码如下:
My thoughts are that getting json to the view shouldn't be a big issue and shouldn't require jQuery, and currently, my page source looks like:
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
我不理解& quot符号(也许就是语法错误的来源),但是当我渲染:json => @nodes.to_json
时,页面会渲染一个有效的普通json:
I dont understand the " symbols (maybe thats where the syntax error is coming from) but when I do render :json => @nodes.to_json
, the page renders a normal json that is valid:
[{"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)
时,它给了我一个非法的令牌错误.
Note: I've also tried doing var stuff = '<%= @json.to_json
%> but when I do var json = JSON.parse(stuff)
, it gives me an illegal token error.
有人可以帮我吗?非常感谢!
Can someone please help me with this? Thanks so much!
推荐答案
这是Rails html编码的字符串,这是Rails 3中的默认设置.
This is Rails html-encoding your string as is default in Rails 3.
您需要将JSON标记为html_safe
:
You need to mark your JSON as html_safe
:
var stuff = <%= @json.to_s.html_safe %>
请注意,由于as_json
给出的是Hash而不是字符串,因此需要.to_s
.您可以改为:
Note that .to_s
is needed because as_json
gives Hash instead of string. You could do this instead:
# in controller
@json = @nodes.to_json(:only => [:ID, :Lat, :Lon])
#and in view
var stuff = <%= @json.html_safe %>
这篇关于Rails中奇怪的JSON Javascript问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!