Hi all,

I've started using Ajax in my Django sites. I'm using Jquery (and I
love it!), but here it doesn't really matter which JS library you use,
I'd just like to know your opinions on the best way to go to handle it
on the server side.

I'm gonna tell you how I do it, then I'd really appreciate if you
could share the way you do it. There are probably many good
approaches, but maybe we could find some common ground that could for
example be put online on the wiki.

What I do is mostly cosmetic to keep things tidy:

1) I put all my ajax views in a separate file 'ajax-views.py'. By
"ajax views" I mean all views that are called by a javascript, as
opposed to the traditional views which are called through the
browser's address bar.
The structure then looks like this:
myapp
   |_ ajax-views.py
   |_ models.py
   |_ urls.py
   |_ views.py

2) In the URLConf I also separate traditional views from ajax views:

from django.conf.urls.defaults import *

# Traditional views
urlpatterns = patterns('myapp.views',
   url(r'^$', 'home'),
   url(r'^news/$', 'list_news'),
)

# AJAX views
urlpatterns += patterns('myapp.ajax-views',         # Don't forget the
'+=' sign here.
   url(r'^ajax/news/latest/$', 'ajax_latest_news'),
   url(r'^ajax/news/add/$', 'ajax_add_news'),
)

Note that I also add the prefix "ajax/" in the URLs for the ajax
views.

3) The ajax views can look like this:

from django.utils import simplejson

def ajax_latest_news(request):
    ...
    latest_news = ...
    json = simplejson.dumps(latest_news)
    return HttpResponse(json, mimetype='application/json')

def ajax_add_news(request):
    ...
    results = {'success':True}
    json = simplejson.dumps(results)
    return HttpResponse(json, mimetype='application/json')

Please let me know your thoughts ;)
Cheers!

Julien
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to