2015-10-08 42 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