• AJAX in Django with jQuery


    AJAX in Django with jQuery | webcloud

    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:

  • 相关阅读:
    idea.vmoption文件修改之后,Idea无法打开的问题
    py学习:namedtuple 具名元组
    py学习:可变对象作为函数参数默认值
    图解Python变量与赋值(转)
    github 提交的认证方式
    让 IDEA 忽略某个文件夹的方式
    在 Windows 上开启 telnet 功能
    Java原生日志 Java.util.logging
    转:Python简史
    Maven无法下载fastdfs-client-java依赖,Dependency 'org.csource:fastdfs-client-java:1.27-SNAPSHOT' not found.
  • 原文地址:https://www.cnblogs.com/lexus/p/2487056.html
Copyright © 2020-2023  润新知