2015-10-08 43 views
-1

我有轨控制器:接受JSON在CoffeeScript中的AJAX响应

class TrafficVolumeController < ApplicationController 
    def test 
    render json: Traffic.all 
    end 
end 

我可以看到它返回JSON: enter image description here

在此AJAX请求:

$.ajax '/traffic_volume/test', 
    type: 'GET' 
    dataType: 'json' 
    json: true 
    success: (data, textStatus, jqXHR) -> 
    $('body').append "Successful AJAX call: #{data}" 

但数据的任何类型和在浏览器中,我可以看到:

enter image description here

所以问题是如何使用这个data参数。我是否必须将其转换为其他类型,或者我需要在请求中更改HTTP标头或在rails控制器中进行更改。真的需要你的帮助,因为我已经花了很多时间了。谢谢!

回答

1

你在页面上观察到的是对象的默认字符串表示,这不是很有帮助。

试试这个,应该是更好:

console.log "Successful AJAX call: ", data 

你那data,它是一个数组,对不对?如果是这样,这应该也可以工作

$('body').append(data[0].year) # or whatever you were going to do 
           # in the first place 
+0

谢谢!是的,它是阵列。我对Anything类型有点困惑。没有马上得到,我可以像数组一样使用数据对象 – Iurii