2016-08-04 81 views
0

我想提交一個ajax post請求到一個控制器中的create動作,但我得到undefined而不是ajax success函數中的json響應。我需要一個json響應,因爲我正在構建一個單頁面應用程序。我正在使用render :json => {name: "jim"}.to_json。這是否是正確的方式去做,或者是否有一些關於我缺少的Ajax請求的基礎知識?Rails ajax post response undefined

任何幫助將不勝感激。

客戶端AJAX POST請求:

submit_click: -> 
    $.post "/responses", 
     type: "POST" 
     dataType: "json" 
     contentType: "application/json" 
     charset="utf-8" 
     response: 
     image_id: @image_name 
     data: @data_pool 
     success: (json) -> 
     console.log json 

行動中應對控制:

def create 
    @response = Response.new(response_params) 
    if @response.save 
     count = count_completed_responses 
     if count < 20 
     render :json => {name: "jim"}.to_json 
     end 
    end 
    end 

編輯:我可以看到在Chrome開發者控制檯的網絡選項卡來通過響應 - {名稱:「吉姆」}。爲什麼我不能在ajax成功回調中訪問它?

2日編輯:事實上,我這個利用上班$post功能後,以下:

.done (data) 
    console.log data 

人知道爲什麼工作和其他方式不?

+0

您無需使用'類型: 「POST」'。該方法本身將發出POST請求。 –

+0

'charset =「utf-8」'也是錯誤的語法。我不知道你怎麼能打電話給服務器:) –

回答

0

它應該像下面

submit_click: -> 
    $.post "/responses", 
    contentType: 'application/json; charset=utf-8' 
    dataType: 'json' 
    response: 
     image_id: @image_name 
     data: @data_pool 
    success: (json) -> 
     console.log json 

希望它會爲你工作

+0

謝謝,但不幸的是,沒有工作 - 控制檯日誌仍然輸出未定義 – RobotEyes