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])
在我看来,我try 过:
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 {"
分
I have also tried using jquery and using respond_to within the controller, but that doesn't seem to work either.
我的 idea 是,将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:
[{"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.
有人能帮我吗?非常感谢!