How to output JSON from within Django and call it with jQuery from a cross domain?

Posted by Emre Sevinç on Stack Overflow See other posts from Stack Overflow or by Emre Sevinç
Published on 2010-04-30T08:26:51Z Indexed on 2010/04/30 9:37 UTC
Read the original article Hit count: 360

Filed under:
|
|

For a bookmarklet project I'm trying to get JSON data using jQuery from my server (which is naturally on a different domain) running a Django powered system.

According to jQuery docs: "As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback." And for example I can test it successfully in my Firebug console using the following snippet:

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&    format=json&jsoncallback=?",
        function(data){
          alert(data.title);
        });

It prints the returned data in an alert window, e.g. 'Recent uploads tagged cat'. However when I try the similar code with my server I don't get anything at all:

$.getJSON("http://mydjango.yafz.org/randomTest?jsoncallback=?",
        function(data){
          alert(data.title);
        });

There are no alert windows and the Firebug status bar says "Transferring data from mydjango.yafz.org..." and keeps on waiting. On the server side I have this:

def randomTest(request):
    somelist = ['title', 'This is a constant result']
    encoded = json.dumps(somelist)
    response = HttpResponse(encoded, mimetype = "application/json")
    return response

I also tried this without any success:

def randomTest(request):
    if request.is_ajax() == True:
        req = {}
        req ['title'] = 'This is a constant result.'
        response = json.dumps(req)
        return HttpResponse(response, mimetype = "application/json")

So to cut a long story short: what is the suggested method of returning a piece of data from within a Django view and retrieve it using jQuery in a cross domain fashion? What are my mistakes above?

© Stack Overflow or respective owner

Related posts about django

Related posts about jquery-ajax