开发者

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

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开发者_如何学JAVA. '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?


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)?


From Django 1.7 onwards, you can simply use JsonResponse.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜