Ajax提交json数据,通过jquery.cookie.js插件解决csrf_token问题

html代码和js代码

<!doctype html>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax提交Json数据</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="../static/jquery.cookie.js"></script>
    <script>
        $(function () {
            $('.btn').click(function () {
                $.ajax({
                    url: '',
                    type: 'post',
                    contentType: 'application/json; charset=utf-8',
                    headers: {"X-CSRFToken": $.cookie('csrftoken')},
                    data: JSON.stringify(GetJsonData()),
                    dataType: "json",
                    success: function (res) {
                        console.log(res);
                    },
                    error: function (err) {
                        console.log(err);
                    }
                })
            });

            // 生成Json数据
            function GetJsonData() {
                var json = {
                    username: $("input[name='username']").val(),
                    password: $("input[name='password']").val(),
                    status: "ok",

                };
                return json;
            }
        })
    </script>
</head>
<body>
<form>
    <div>
        <label for="username">用户:</label>
        <input type="text"  name="username">
    </div>
    <div>
        <label for="password">密码:</label>
        <input type="text"  name="password">
    </div>
    <!-- 
    阻止form表单默认发送请求方式:
    1.使用a标签,然后加btn样式(必须先引入bootstrap)
    2.使用input标签,type设置为button
    -->
    <a class="btn btn-primary btn-sm">提交</a>
    <!--
        <input type="button" value="提交">
    -->
</form>
</body>
</html>

Django后台处理:

def home(request):
    import json
    # 前段发来的数据要先解码,在反序列化
    ret = json.loads(request.body.decode('utf8'))
    print('前段发来的字典:',ret)
    # {'username': 'jack', 'password': '123456', 'status': 'ok'}
    print('前段发来的消息:',ret['username'],ret['password'],ret['status'])
    # jack 123456 ok
    return render(request, 'index.html')