2012-07-12 32 views
1

我正在做一些HTML5上傳和遇到一個問題,我似乎無法弄清楚。拿這個功能代碼:Rails與json的respond_to問題

if @image.save 
    render :json => {:status => "Successfully uploaded image!"} 
else 
    render :json => {:status => "Something went wrong with your upload!"} 
end 

這是行之有效的,它確實如其所料。然而,當我添加的respond_to趕上HTML請求,它徹底失敗(雖然HTML部分工作。)

respond_to do |format| 
    if @image.save 
     format.html {redirect_to(edit_product_path(@image.product), :notice => "Your image was added successfully.")} 
     format.json {render :status => "Successfully uploaded image!"} 
    else 
     format.html {redirect_to(edit_product_path(@image.product), :alert => "An error occurred while attempting to upload your image. Please try again.")} 
     format.json {render :status => "Something went wrong with your upload!"} 
    end 
end 

任何想法可能是錯誤的?我覺得我正在俯視簡單的事情。謝謝。

編輯 - 已解決的問題

我想這是我一直俯瞰着愚蠢的事。原來請求是HTML,而不是JSON,這是因爲上傳需要內容類型爲multipart/form-data,respond_to觸發了HTML。

+0

什麼錯誤消息? – Dty 2012-07-12 04:09:12

+0

Firebug只顯示: JSON.parse:意外字符 return window.JSON.parse(data); – Orlando 2012-07-12 04:14:29

回答

0

你需要渲染響應爲JSON

# old 
format.json {render :status => "Successfully uploaded image!"} 

# new 
format.json { render(:json => { :status => "Successfully uploaded image!" }) } 
2

渲染需要一個狀態代碼,所以下面將不工作

format.json {render :status => "Something went wrong with your upload!"} 

你可以寫出來作爲

format.json {render :error => "Something went wrong with your upload!", :status => :bad_request }