Wed 6 Dec 2006
While it’s nothing major, Rails recently got the ability to render JSON a little more easily:
- render :json => items.to_json
This sets the content type to “application/json” and renders whatever text passed. But wait! There’s more! You can also start implementing Yahoo!-esque REST web services with JS callbacks like so:
- class PeopleController < ActionController::Base
- …
- def show
- @person = Person.find(params[:id])
- respond_to do |format|
- format.html
- format.xml { render
ml => @person.to_xml } - # this can be called with /people/1.json?callback=loadPerson
- # and will generate ‘loadPerson({name: "Brian", skills: "bowhunting, nunchuck, computer hacking"})’
- format.json { render :json => @person.to_json, :callback => params[:callback] }
- end
- end
- …
- end
You might wonder why I’d bother blogging about this. It’s because this marks my 5th patch into Rails (well, maybe 4.5 since it was originally posted by someone else and I updated it with tests). w00t!
January 23rd, 2007 at 16.06
Thanks a lot for patching this into Rails! I just used it and it’s fantastic.
March 16th, 2008 at 08.16
What if you want to send a link back to your current site via a third party site, or basically generate a link that avoids cross-browser security issues with normal javascript?
March 16th, 2008 at 08.20
Wanted to say this differently. I want to use JSON to do a POST, not a GET. So I want to POST a person using CREATE, not GET a person using SHOW. Does anyone have an example like that?
March 19th, 2008 at 08.20
@Brian: This patch really only has to do with returning JSON from the server and nothing to do with GET/POST etc. FF3 includes a X-Site version of XHR, but I don’t know much about it. Otherwise you’re stuck with script tags which only do GET.