AJAX in Django with jQuery
2012-05-07 10:55
477 查看
AJAX in Django with jQuery | webcloud
Published: July 2009
Note: This article has been reviewed as of 2011 and now applies to Django 1.3 and jQuery 1.5.
Unlike some other web application frameworks, Django (thankfully) doesn't implement, or bundle with any JavaScript library. However, In this article I'll be using jQuery for the sake of simplicity.
jQuery and most other "major" libraries will set the HTTP_X_REQUESTED_WITH header to "XMLHttpRequest" for you, so the Django is_ajax() method will return true. Now that you can determine wether a request is done by ajax it's simple to write views in an
unobtrusive manner.
in either JSON or XML.
Serializing Django objects
JSON in JavaScript
jQuery AJAX API
AJAX in Django with jQuery
Here's a few examples on how to implement AJAX functionality in a django application, using the jQuery JavaScript library.Published: July 2009
Note: This article has been reviewed as of 2011 and now applies to Django 1.3 and jQuery 1.5.
Unlike some other web application frameworks, Django (thankfully) doesn't implement, or bundle with any JavaScript library. However, In this article I'll be using jQuery for the sake of simplicity.
A basic example
Let's start out with some very simple code, in the views.py of your applicationfrom django.http import HttpResponse def xhr_test(request): if request.is_ajax(): message = "Hello AJAX" else: message = "Hello" return HttpResponse(message) # Your URL pattern could be as simple as (r'^xhr_test
,'your_project.your_app.views.xhr_test'),
jQuery and most other "major" libraries will set the HTTP_X_REQUESTED_WITH header to "XMLHttpRequest" for you, so the Django is_ajax() method will return true. Now that you can determine wether a request is done by ajax it's simple to write views in an
unobtrusive manner.
The jQuery part
(function() { $.get("/sandbox/xhr_test", function(data) { alert(data); }); });
Sending Post Data
Here's another example on how you would typically send POST data to a view.$.post("/sandbox/xhr_test", { name: "Monty", food: "Spam" }, function(data) { alert(data); } );Now you can access the post data in your view. It's good practice to check that the request method is really a POST before trying to access the data:
from django.http import HttpResponse def xhr_test(request): if request.is_ajax(): if request.method == 'GET': message = "This is an XHR GET request" elif request.method == 'POST': message = "This is an XHR POST request" # Here we can access the POST data print request.POST else: message = "No XHR" return HttpResponse(message)
CSRF Protection
Since django 1.2 you'll have to take certain measures to avoid being caught in the CSRF protection filter when doing AJAX post Requests.JSON and XML
When working with AJAX, you usually want to return something more useful than plain text. Let's modify our above function to return a Django object serializedin either JSON or XML.
from django.http import HttpResponse from django.core import serializers from your_app.models import ExampleModel def xhr_test(request, format): if request.is_ajax(): if format == 'xml': mimetype = 'application/xml' if format == 'json': mimetype = 'application/javascript' data = serializers.serialize(format, ExampleModel.objects.all()) return HttpResponse(data,mimetype) # If you want to prevent non XHR calls else: return HttpResponse(status=400) # urls.py (r'^xhr_test/(?P<format>\w+)/ ,'your_project.your_app.views.xhr_test'),Now you could do a request to either /xhr_test/xml for an XML response or /xhr_test/json for a JSON response, if the request is not AJAX however, it will return a HTTP 400 BAD request header.
Python and JSON
Python has a JSON module, but Django already comes with simplejson. Further more, Python dictionaries are quite similar to the JSON data structure itself, which makes everything dead simple. Run "python manage.py shell" in your project root and try the following:>>> from django.utils import simplejson >>> test_dict = {'a': 1, 'b': 2, 'john' : 'done', 'jane' : 'doe'} >>> simplejson.dumps(test_dict) '{"a": 1, "john": "done", "b": 2, "jane": "doe"}'This article covered the very very basics. There's a lot more on how to handle the response in jQuery properly and how to serialize objects with Django. I can recommend you take a look at the following articles for further information:
Serializing Django objects
JSON in JavaScript
jQuery AJAX API
相关文章推荐
- Ajax (jquery)实现智能提示搜索框(in Django)
- [Study Note] AJAX basics with jQuery in ASP.NET
- How to POST a django form with AJAX & jQuery
- Native Ajax in Django and jQuery
- Using AJAX with JQuery Mobile
- jquery/ajax in jsp
- about springmvc intergation jquery with ajax &no-ajax version
- Getting started with ASP.NET AJAX in Visual Web Developer
- Send and Receive JSON objects to Web Service Methods using jQuery AJAX in ASP.Net
- Creating Vista Gadgets: Using HTML, CSS and JavaScript with Examples in RSS, Ajax, ActiveX (COM) and
- deploy django with url prefix in nginx
- 如何从jQuery的ajax请求中删除X-Requested-With
- Struts Work With AJAX ON JQUERY
- 十九 Django 1.5.4 jquery ajax bootstrap
- [转]jQuery AJAX pagination plugin with ASP.NET Server Side
- AJAX with JSP and Servlet using Jquery Example
- 使用Python的Django框架结合jQuery实现AJAX购物车页面
- ajax+jquery+django
- 使用Python的Django框架结合jQuery实现AJAX购物车页面
- Easy Ajax with jQuery[令狐葱翻译版Part1]