• 解决Django中在.js文件中用ajax请求后端,找不到CSRF问题


    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;
    }
    
    
    var USERNAME = '';
    $('document').ready(function(){
    
    
        $('#login_submit').click(function(){
            var csrftoken = getCookie('csrftoken');
            var username = $('#username').val();
            var password = $('#password').val();
    
            $.ajax({
                cache: false,
                type: "POST",
                url: "/signin/",
                dataType:'json',
                async: true,
                data:{
                    username: username, //用户名
                    password: password  //密码
                },
                success: function(data) {
                     if (data.status == 'fail') {
                            alert('用户名或密码错误')
                     }
                     if (data.status == 'fail1') {
                         alert('用户名必填并且密码必须要五位以上')
                     }
                     if(data.status == 'success') {
                         window.location.href = "/index";
                     }
    
    
                },
                beforeSend: function(xhr, settings) {
                  xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            });
        });
  • 相关阅读:
    (C/C++学习笔记) 十四. 动态分配
    (C/C++学习笔记) 十三. 引用
    (C/C++学习笔记) 十二. 指针
    (C/C++学习笔记) 十一. 数组
    (C/C++学习笔记) 十. 函数
    (C/C++学习笔记) 九. 变量的存储类型
    (C/C++学习笔记) 八. 程序控制语句
    并发编程之多进程
    网络编程之Socket
    异常处理
  • 原文地址:https://www.cnblogs.com/zhaoyingjie/p/6434710.html
Copyright © 2020-2023  润新知