Streamlining JSON processing with Prototype 1.6
Saturday, February 9th, 2008The other day I was doing some refactoring. I became aware that with Prototype 1.6, there comes a nice Ajax.Response object as the first argument of all Ajax callbacks. And as the documentation points out, the “responseJSON” property is “The JSON body of the response if the content-type of the request is set to application/json. null otherwise.”
I used to process the JSON responses from Grails the old way using the “response.responseText.evalJSON()” thing. So it looks like this process is nicely streamlined now. And now that I’ve replaced the stock prototype in Grails with the new 1.6 version, this is a low hanging fruit to make the code nicer. So why not?
In your Grails controller code, simply replace all occurrences of
render(contentType:"text/json", ...
With
render(contentType:"application/json", ...
And in your javascript, replace all
response.responseText.evalJSON()
with
response.responseJSON
Congratulations! Your code has just become one step more concise and prettier.
So here’s just a little tip I feel like sharing with you.
P.S. Grails 1.0 has been out a couple days now. Great news for all!