Weird JSON Javascript problem in Rails

前端 未结 2 689
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 02:34

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]) 
<         


        
相关标签:
2条回答
  • 2021-02-05 02:48

    I think you need to put quotes around it, then you can ask jquery to parse the string into JSON.

    0 讨论(0)
  • 2021-02-05 03:00

    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 %>
    
    0 讨论(0)
提交回复
热议问题