Django如何支持JSON式AJAX
其實滿簡單的
Django已經內建simplejson模組 只要import進來就好了
底下是個傳遞JSON物件的範例
from django.utils import simplejson
def ajax_view(request):
jsondict = {'a':request.session['a'],'b':'hi'}
return HttpResponse(simplejson.dumps(jsondict))
如此你就會在javascript端收到一個含有a,b這兩個屬性的物件.
update: A tip using via decorator from mailing list
> def json_wrap(func):
> def _json_wrap(*args, **kwargs):
> return HttpResponse(dumps(func(*args,**kwargs)),mimetype="application/json")
> return _json_wrap
and then you can use it like:
> @json_wrap
> def foo(request,a,b,c):
> return dict(a=a,b=b,c=c)
update 2:
how to serialize the QuerySet object.
http://www.djangoproject.com/documentation/serialization/
沒有留言:
張貼留言