Django 结合 jQuery 实现 AJAX(二)

上一篇我们使用了 jQuery 的 get 方法来实现了 AJAX,本篇我们采用 post 方法来实现。

编写 test.html


    

姓名:

年龄:

get 方法最大的不同,由于 django 中对 post 增加了 CSRF 的保护,所以其 views.py 的响应函数需要加上 @csrf_exempt 装饰器,该装饰器意味着在该方法中取消 CSRF 保护:

from django.views.decorators.csrf import csrf_exempt

# AJAX的post方法
@csrf_exempt
def ajax_post(request):
    # 获取前端输入的内容
    name = request.POST.get('name')

    try:
        student = Student.objects.get(name=name)
        age = student.age
    except:
        age = "该姓名不存在"

    data = {}
    data['name'] = name
    data['age'] = age

    return JsonResponse(data)

其余步骤和 get 方法一摸一样。




以上方法明显是不安全的,为了使 AJAX 的 post 方法拥有 CSRF 保护,我们需要在页面加上以下这段 js 代码:

jQuery(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

view.py 中则不需使用 csrf_exempt 装饰器:

from django.views.decorators.csrf import csrf_exempt

def ajax_post(request):
    # 获取前端输入的内容
    name = request.POST.get('name')

    try:
        student = Student.objects.get(name=name)
        age = student.age
    except:
        age = "该姓名不存在"

    data = {}
    data['name'] = name
    data['age'] = age

    return JsonResponse(data)

你可能感兴趣的:(Django 结合 jQuery 实现 AJAX(二))