如何在Rails中发送简单的json响应?
我需要发送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 )
在我的控制器中:
def checkname respond_to do |format| format.jsonr do render :json => { :status => :ok, :message => "Success!", :html => "congrats" }.to_json end end end
但是屏幕是空的,当我组成对此操作的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
我做错了什么?
不确定处理自定义MIME,但是对于渲染JSON,这应该工作:
def testme respond_to do |format| msg = { :status => "ok", :message => "Success!", :html => "..." } format.json { render :json => msg } # don't do msg.to_json end end
如果您说明您正在使用哪个版本的Ruby和Rails,它也可能有所帮助。
我通常使用此方法返回json数据:
msg = {:token => token, :courseId => courseId} render :json => msg
一个简单的方法是:
def my_action render :json => {:name => "any name"} end