Python/Django JSONP Response class
Aug 15, 2010
Dick Brouwer
1 minute read

A few weeks ago I wrote a bookmarklet for listcharming that loads a popup on any site you visit and makes it really easy to create a custom wedding gift. It scans all the pictures, filters out icons etc., and allows you to submit this image plus additional data like price and description to your registry.

Unfortunately this involves a cross-domain javascript call, since you’re calling the script from a different domain. The JsonpResponse class below handles the trick of wrapping the JSON response in a callback function.

On the JS side, jQuery’s getJSON function will work automatically if you append ?jsoncallback=? to the url (the jsoncallback name needs to match the callback parameter in the JsonpResponse class).

class JsonpResponse(HttpResponse):
    def __init__(self, data, callback):
        json_encoder = LazyEncoder(ensure_ascii=False)
        json = json_encoder.encode(data)
        jsonp = "%s(%s)" % (callback, json)
            self, jsonp,

comments powered by Disqus