Rails 中奇怪的 JSON Javascript 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5970419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Weird JSON Javascript problem in Rails
提问by readmymsg123
I'm trying to get my JSON from my controller to my view. In my controller I am doing:
我正在尝试将我的 JSON 从我的控制器获取到我的视图中。在我的控制器中,我正在做:
@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 %>
and all of those give me an error. I usually get an "Unexpected Syntax Error &" or "Unexpected Syntax Error {"
所有这些都给了我一个错误。我通常会得到一个"Unexpected Syntax Error &" or "Unexpected Syntax Error {"
I have also tried using jquery and using respond_to within the controller, but that doesn't seem to work either.
我也尝试过在控制器中使用 jquery 和 respond_to,但这似乎也不起作用。
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:
我的想法是让 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
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:
我不明白 " 符号(也许这就是语法错误的来源)但是当我渲染 : 时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}}
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.
注意:我也尝试过var stuff = '<%= @json.to_json
%> 但是当我这样做时var json = JSON.parse(stuff)
,它给了我一个非法令牌错误。
Can someone please help me with this? Thanks so much!
有人可以帮我解决这个问题吗?非常感谢!
回答by Laas
This is Rails html-encoding your string as is default in Rails 3.
这是 Rails 对您的字符串进行 html 编码,这是 Rails 3 中的默认设置。
You need to mark your JSON as html_safe
:
您需要将您的 JSON 标记为html_safe
:
var stuff = <%= @json.to_s.html_safe %>
Note that .to_s
is needed because as_json
gives Hash instead of string. You could do this instead:
请注意,这.to_s
是必需的,因为as_json
给出 Hash 而不是字符串。你可以这样做:
# in controller
@json = @nodes.to_json(:only => [:ID, :Lat, :Lon])
#and in view
var stuff = <%= @json.html_safe %>
回答by JSager
I think you need to put quotes around it, then you can ask jquery to parse the string into JSON.
我认为您需要在它周围加上引号,然后您可以要求 jquery 将字符串解析为 JSON。