17-ajax向後端提交POST請求

ajax登陸示例

urls.pycss

from django.conf.urls import url
from django.contrib import admin
from app01 import views
 
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login_ajax/$', views.login_ajax, name='login_ajax'),
    url(r'^index/$', views.index, name='index'),
]
View Code

views.pyhtml

from django.shortcuts import render, HttpResponse, redirect
import json
 
 
def index(request):
    return HttpResponse('this is index')
 
 
def login_ajax(request):
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        ret = {"status": 0, 'url': ''}
        if user == "alex" and pwd == "123":
            ret['status'] = 1
            ret['url'] = '/index/'
        return HttpResponse(json.dumps(ret))
 
    return render(request, "login_ajax.html")
views.py

login_ajax.htmljquery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>登陸</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
    <link rel="stylesheet" href="/static/css/signin.css">
</head>
<body>
 
<div class="container">
 
    <form class="form-signin" action="{% url 'login' %}" method="post">
        {% csrf_token %}
        <h2 class="form-signin-heading">請登陸</h2>
        <label for="inputUser" class="sr-only">用戶名</label>
        <input type="text" id="inputUser" class="form-control" placeholder="用戶名" required="" autofocus="" name="user">
        <label for="inputPassword" class="sr-only">密碼</label>
        <input type="password" id="inputPassword" class="form-control" placeholder="密碼" required="" name="pwd">
        <div class="checkbox">
            <label>
                <input type="checkbox" value="remember-me"> 記住我
            </label>
        </div>
        <input class="btn btn-lg btn-primary btn-block" id="login" value="登錄">
    </form>
 
</div> <!-- /container -->
 
 
<script src="/static/jquery-3.3.1.min.js"></script>
<script>
 
    $('#login').click(function () {
        $.ajax({
            url: '/login_ajax/',
            type: 'post',
            data: {
                csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
                user: $('[name="user"]').val(),
                pwd: $('[name="pwd"]').val()
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.status) {
                    window.location = data.url
                }
                else {
                    alert('登錄失敗')
                }
            }
        })
    })
</script>
 
</body>
</html>
login_ajax.html

靜態文件須要配置,使用了jQuery和Bootstrap。git

CSRF跨站請求僞造

 

方式一

將 csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val() 放在POST的請求體中。github

示例中就是使用的這種方式。ajax

 

方式二

給ajax的請增長X-CSRFToken的請求頭,對應的值只能是cookie中的csrftoken的值。django

因此咱們要從cookie中提取csrftoken的值,jQuery不能去cookie,咱們使用jquery.cookie的插件。點擊下載jquer.cookie插件json

HTML中導入jquery.cookie.js。 bootstrap

<script src="/static/jquery-3.3.1.min.js"></script>
<script src="/static/jquery.cookie.js"></script>
<script>
 
    $('#login').click(function () {
        $.ajax({
            url: '/login_ajax/',
            type: 'post',
            headers:{ "X-CSRFToken":$.cookie('csrftoken') },
            data: {
                user: $('[name="user"]').val(),
                pwd: $('[name="pwd"]').val()
            },
            success: function (data) {
                data = JSON.parse(data);
                if (data.status) {
                    window.location = data.url
                }
                else {
                    alert('登錄失敗')
                }
            }
        })
    })
</script>
方式二

 

方式三cookie

使用$.ajaxSetup()給全局的ajax添加默認參數。

能夠按照方式一設置data,也能夠按照方式二設置請求頭。

$.ajaxSetup({
    data: {
        csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
    }
});





$.ajaxSetup({
    headers: {"X-CSRFToken": $.cookie('csrftoken')},
});
方式三

 

方式四

官方推薦方法(用到jquery.cookie插件):

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
 
$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});
方式四
相關文章
相關標籤/搜索