Thursday, 7 August 2008

Prototype, JSON and Appengine

I am using prototype in a Google Appengine project, and while it worked on my development machine, after deploying it onto the Google infrastructure prototype wasn't parsing the JSON responses anymore.

In my code, I was returning the JSON in the response text (as opposed to using X-JSON response header). The Content-Type response header was set as application/json and my javascript code used Ajax.Request() with the parameter evalJSON:true so as to parse the response text.

Running locally with the everything worked okay. However when running the deployed app, the Content-Type header was no longer being set - meaning that prototype would never parse the response text.

I'm not sure why Content-Type doesn't get set when running on the Google infrastructure yet it works on the development server. But, luckily when using Ajax.Request, you can specify evalJSON:'force' so that prototype parses the response regardless of the content-type.

Server ajax response code:
result = func(args)
# content type doesn't work when deployed
self.response.headers.add_header("Content-Type", 'application/json')
Javascript Ajax request:
new Ajax.Request('/rpc',{parameters:{action:'add'}
,method:'post',evalJSON:'force',onSuccess:function(transport) {
var result=transport.responseJSON;
Response headers from Google:
Content-Type:    text/html; charset=utf-8
Cache-Control:    no-cache
Content-Encoding:    gzip
Date:    Wed, 06 Aug 2008 09:56:05 GMT
Server:    Google Frontend
Content-Length:    82


Post a Comment