本文介绍了如何在Rails中发送简单的json响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要发送json响应取决于输入中用户输入的数据,但是我无法发送简单的json请求.
I need to send json response depends on user entered data in input, but I'm failing to send simple json request.
我关注了这篇文章- http://paydrotalks.com/posts/45标准的json-response-for-rails-and-jquery .
添加了MimeType:
Added 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 => "<b>congrats</b>"
}.to_json
end
end
end
但是屏幕是空的,这是我对这个动作进行GET响应时来自fiddler2的响应代码:
but the screen is empty and here is response code from fiddler2 when I composed GET response to this action:
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,这应该可以:
Not sure about dealing with custom MIME, but as for rendering JSON, this should work:
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版本,这也可能会有所帮助.
Also it might help if you state which version of Ruby and Rails you are using.
这篇关于如何在Rails中发送简单的json响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!