如何在Rails中发送简单的json响应?

MID*_*MID 32 json ruby-on-rails

我需要发送json响应取决于用户在输入中输入的数据,但我没有发送简单的json请求.

我按照这篇文章 - http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery.

添加了MimeType:

Mime::Type.register_alias "application/json", :jsonr, %w( text/x-json )  
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

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

但屏幕是空的,当我对此操作组成GET响应时,这里是来自fiddler2的响应代码:

    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
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Luk*_*kal 35

不确定处理自定义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
Run Code Online (Sandbox Code Playgroud)

如果您说明您正在使用哪个版本的Ruby和Rails,它也可能有所帮助.

  • 我不知道为什么,但你的代码不适合我.我的版本正在工作`render:json => {:status =>:ok,:message =>"Success!",:html =>"... insert html ..."}` (4认同)

dal*_*ate 19

我通常使用此方法返回json数据:

msg = {:token => token, :courseId => courseId}
render :json => msg
Run Code Online (Sandbox Code Playgroud)


Som*_*rma 7

一种简单的方法是:

def my_action 

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

end
Run Code Online (Sandbox Code Playgroud)


小智 5

最简单的方法是 render json: {foo: 'bar'}