Reputation: 1825
I need to send json response depends on user entered data in input, but I'm failing to send simple json request.
I followed this article - http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery .
Added MimeType:
Mime::Type.register_alias "application/json", :jsonr, %w( text/x-json )
and in my controller:
def checkname
respond_to do |format|
format.jsonr do
render :json => {
:status => :ok,
:message => "Success!",
:html => "<b>congrats</b>"
}.to_json
end
end
end
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
What I'm doing wrong ?
Upvotes: 40
Views: 86574
Reputation: 569
One Simple way is:
def my_action
render :json => {:name => "any name"}
end
Upvotes: 10
Reputation: 481
I usually use this method to return json data:
msg = {:token => token, :courseId => courseId}
render :json => msg
Upvotes: 25
Reputation: 2562
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
Also it might help if you state which version of Ruby and Rails you are using.
Upvotes: 38