Weird JSON Javascript problem in Rails
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 %>
and all of those give me an error. I usually get an "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.
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
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_jso开发者_运维百科n
%> 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!
This is Rails html-encoding your string as is default in Rails 3.
You need to mark your JSON as 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:
# in controller
@json = @nodes.to_json(:only => [:ID, :Lat, :Lon])
#and in view
var stuff = <%= @json.html_safe %>
I think you need to put quotes around it, then you can ask jquery to parse the string into JSON.
精彩评论