2012-09-12 46 views
24

我需要發送json響應取決於用戶在輸入中輸入的數據,但我無法發送簡單的json請求。如何在Rails中發送簡單的json響應?

我關注了這篇文章 - http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery

添加Mime類型:

Mime::Type.register_alias "application/json", :jsonr, %w(text/x-json) 

,並在我的控制器:

def checkname 
    respond_to do |format| 
    format.jsonr do 
     render :json => { 
     :status => :ok, 
     :message => "Success!", 
     :html => "<b>congrats</b>" 
     }.to_json 
    end 
    end 
end 

但屏幕是空的,這裏是從fiddler2響應代碼時,我由GET響應這個動作:

HTTP/1.1 406 Not Acceptable 
    Content-Type: text/html; charset=utf-8 
    X-UA-Compatible: IE=Edge 
    Cache-Control: no-cache 
    X-Request-Id: 14a8467908d9ce322d054607efdacf92 
    X-Runtime: 0.011000 
    Content-Length: 1 
    Connection: keep-alive 
    Server: thin 1.4.1 codename Chromeo 

我做錯了什麼?

+1

你確定你mime_types.rb版後重新啓動您的應用程序?並確保在最後使用'.jsonr'通過URL訪問您的動作,如:'http:// localhost:3000/checkname.jsonr'。 – jdoe

+0

@jdoe,是的。你是對的。你可以看看這裏http://stackoverflow.com/questions/12382680/how-to-send-json-response-from-controller-to-jquery-and-inspect-it - 這就是爲什麼我需要發送json請求。 – MID

+0

我到底在哪裏? :)你解決了這個問題還是存在?我試過你的代碼,並將瀏覽器指向'http:// localhost:3000/checkname.jsonr'給我JSON響應(application/json)。 – jdoe

回答

32

不知道關於處理MIME定製,但渲染JSON,這應該工作:

def testme 
    respond_to do |format| 
    msg = { :status => "ok", :message => "Success!", :html => "<b>...</b>" } 
    format.json { render :json => msg } # don't do msg.to_json 
    end 
end 

此外,如果你的國家的Ruby的版本和Rails你正在使用它可能會有所幫助。

+4

我不知道爲什麼,但是你的代碼不適合我。我的版本正在運行'render:json => { :status =>:ok, :message => 「成功!」, :html =>「...插入html ...」 }' – MID

+0

@MID你在控制器的頂部包括'respond_to:html,:json'嗎? – Chris

11

我通常使用這個方法返回的JSON數據:

msg = {:token => token, :courseId => courseId} 
render :json => msg 
+0

這很簡單! –

1

一個簡單的方法是:

def my_action 

render :json => {:name => "any name"} 

end 
相關問題