AJAX in Django with jQuery
11061 단어 jquery
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 application
from 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 serialized in 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:
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
jQuery 전후 예이 기사에서는 jquery after() 및 before() 메소드의 예를 볼 것입니다. before() 메서드는 선택한 요소 앞에 지정된 콘텐츠를 삽입합니다. after() 메서드는 선택한 요소 뒤에 지정된 콘텐츠...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.