One of the demo sites I was working on this week needed to pass a small amount of JSON back with it’s page results. There are a few ways to do this (and I’d suggest this post, “Loading Content with JSON” as a starting point if you’re looking for ideas), but for simplicity, I decided to take advantage of the automatic X-JSON HTTP Header parsing feature in Prototype 1.5.0. (The Ajax.Request docs address this capability.)
The sample code below demonstrates the use of the X-JSON header with an simple “sticky notes” web app. On the client-side, the JavaScript is quite simple. The second variable in the onSuccess callback handler will be automatically initialized using the data in the X-JSON header:
function display_note(id) {
new Ajax.Request('/api/note/' + id + '/', {
method: 'get',
onSuccess: function(transport, results) {
alert("Note(" + results['id'] + ") `" + results['title'] + "`: " + results['body']);
},
}
);
}
To handle this request, I’m using Django on the server with the following URL pattern:
(r'^api/note/(?P
The `get_note` method implementation looks like this: [NOTE: For production use, you'll want some exception handling, but I removed the error handling to simplify the example.]
def get_note(request, id):
# Fetch the Note from the DB:
note = Note.objects.get(pk=id)
# Create the response object (with some dummy text for now):
response = HttpResponse('Check the X-JSON header.')
# Manually set the X-JSON header using the JSON generated from the Note record:
response['X-JSON'] = cjson.encode(note.__dict__)
# Return the response object:
return response
If you’d like to use this technique on your own sites, there are couple points to remember: