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?
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)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With