2

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?

Emre Sevinç
  • 8,211
  • 14
  • 64
  • 105

2 Answers2

16

This seems to work (I forgot to process the callback parameter!):

Server-side Python / Django code:

def randomTest(request):
    callback = request.GET.get('callback', '')
    req = {}
    req ['title'] = 'This is a constant result.'
    response = json.dumps(req)
    response = callback + '(' + response + ');'
    return HttpResponse(response, mimetype="application/json")

Client-side jQuery code to retrieve this data:

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

Is there a better way to achieve the same effect (more established way in terms of Python and Django coding)?

Emre Sevinç
  • 8,211
  • 14
  • 64
  • 105
  • ,am new to django and jquery ,am trying for a "hello world" jquery using django1.3,From my jquery function how can I call python function(in views.py) – Jisson Sep 30 '11 at 09:44
  • Is 'polls/randomTest' $.getJSON("http://mydjango.yafz.org/polls/randomTest?callback=?" repersents a url in your urls.py? – Jisson Sep 30 '11 at 09:45
  • Can I call a python function directly from jquery function? – Jisson Sep 30 '11 at 09:46
1

From Django 1.7 onwards, you can simply use JsonResponse.

>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'
Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47