Requirement:
There is a simple form that has two input field, one is zip code and another is city. If the zip code is filled, the page will fill the city automatically by getting the relevant city of the zip code in an AJAX way.
Implementation:
1. django-admin.py startproject study
2. cd study
3. python manage.py startapp ajax
4. Edit settings.py, add 'study.ajax' to INSTALLED_APPS.
5. mkdir site_media
6. Download jquery.js from www.jquery.com and copy it to site_media
7. Add the following line to urls.py:
(r'^site_media/(?P<path>.*)$',聽'django.views.static.serve',聽{'document_root':'/home/sting/Django/study/site_media'}),
聽 Note: We will include jquery.js in our html, for this kind of static files, django's handling is different from others. Please see http://www.djangoproject.com/documentation/static_files/ to get more detailed information.
8. cd ajax
9. mkdir templates
聽 Note: This folder is used to put template files. It seems that django can load template files from this folder automatically, so you needn't to configure it in settings.py.
10. Create the following html file named form.html.
<!DOCTYPE聽HTML聽PUBLIC聽"-//W3C//DTD聽HTML聽4.01//EN"聽"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Register聽form</title>
<script聽src="http://localhost:8000/site_media/jquery.js"聽type="text/javascript"></script>
<script聽type="text/javascript">
聽聽function聽getZipData()聽{
聽聽聽聽var聽zipcode聽=聽$('#zip').val();
聽聽聽聽$.get('http://localhost:8000/ajax/getzipdata/'聽+聽zipcode聽+聽'/',聽function(data)聽{
聽聽聽聽聽聽$('#city').attr({'value':data});
聽聽聽聽});
聽聽}
</script>
</head>
<body>
<table>
<form聽actioon=""聽method="post">
<tr><td>Zip:</td><td><input聽id="zip"聽onblur="getZipData()"聽type="text"聽name="zip"/></tr>
<tr><td>City:</td><td><input聽id="city"聽type="text"聽name="city"/></tr>
</form>
</table>
</body>
</html>
11. Edit views.py and add the following methods.
from聽django.http聽import聽HttpResponse
from聽django.core聽import聽serializers
from聽django.shortcuts聽import聽render_to_response
def聽getzipdata(request,聽zipcode):
聽聽if聽zipcode聽==聽'214028':
聽聽聽聽city聽=聽'wuxi'
聽聽else:
聽聽聽聽city聽=聽''
聽聽return聽HttpResponse(city)
def聽register(request):
聽聽return聽render_to_response('form.html',聽{})
12. Add the following lines to urls.py.
(r'^ajax/register/$',聽'study.ajax.views.register'),
(r'^ajax/getzipdata/(\d+)/$',聽'study.ajax.views.getzipdata'),
Visit http://localhost:8000/ajax/register/, you will see the simple form, after fill the zip code and move to city, the city will be filled automatically.
Blogged with Flock
Tags: django, jquery, ajax, python

]]>