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

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

According to the jQuery docs: "As of jQuery 1.2 you can load JSON data located in a different domain if you specify a JSONP callback, which can be done like this:" myurl? callback =? ". jQuery will automatically replace? with the correct method name to invoke your specified callback." And for example, I can successfully test it in the Firebug console with 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 box, for example. "Recent downloads are tagged". However, when I try to use similar code with my server , I get nothing:

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

      

There are no warning windows and the Firebug status bar says "Migrating data from mydjango.yafz.org ..." and keeps waiting. On the server side, I have the following:

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

      

I have 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 the long story short: what is the suggested method of returning a piece of data from a Django view and getting it using jQuery in cross domain mode? What are my mistakes above?

+2


a source to share


2 answers


This seems to work (I forgot to handle 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 (a more established way in terms of Python and Django coding)?

+15


a source


As of Django 1.7 , you can simply use JsonResponse .



>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'

      

+1


a source







All Articles