json

4 views
Skip to first unread message

yozhik

unread,
Sep 24, 2008, 2:13:29 AM9/24/08
to Django users
hi all,

does anyone have a very simple example of how to use json and jquery
to communicate between django and javascript. i'm trying to use
$.getJSON but getting confused what parameters to provide to it. docs
say
getJSON(url,data,func). well, func is my javascript function which
handles data from django. but I am mainly confused about url.

thanks!

Pigletto

unread,
Sep 24, 2008, 3:22:42 AM9/24/08
to Django users
In Python I use:
Class JsonResponse from djangosnippets.org:
-----------------------------------
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.utils import simplejson
from django.core.serializers.json import DjangoJSONEncoder


class JsonResponse(HttpResponse):
def __init__(self, obj):
self.original_obj = obj
HttpResponse.__init__(self, self.serialize(),
content_type='text/javascript')
#self["Content-Type"] = "text/javascript"

def serialize(self):
return(simplejson.dumps(self.original_obj,
cls=DjangoJSONEncoder))
-------------------------------------

View eg. in views.py is like:
-------------------------------------
def a_something(request):
return JsonResponse({'message': 'bla bla bla',
'code':324})
-------------------------------------

Javascript:
-------------------------------------
$.ajax({url:COMMON_URLS.test_url,
type: 'GET',
dataType: 'json',
error: function(data){ alert('Error: '+data); },
success: function(data){ alert('OK! '+data.message+',
'+data.code); }
});
-------------------------------------

COMMON_URLS.test_url is something like below, defined in your
template:
-------------------------------------
<script type="text/javascript">
COMMON_URLS = {
test_url:'{% url a_something_id %}'
}
</script>
-------------------------------------

urls.py like:
-------------------------------------
url(r'^a_something/$', 'views.a_something',
name='a_something_id'),
-------------------------------------

Christian Joergensen

unread,
Sep 24, 2008, 5:05:35 AM9/24/08
to django...@googlegroups.com

`url` is the URL where jQuery will request the JSON data from.

It could be `/json/somefeed/` or whatever you have configured the URL of
your Django view to in urls.py.

Regards,
Christian

--
Christian Joergensen
http://www.technobabble.dk

Reply all
Reply to author
Forward
0 new messages