Ajax请求处理csrf校验三种方式
第一种:
<body>
{% csrf_token %}
   
<button id="d1">ajax请求</button>    
<script>
    $('#d1').click(function (){
         $.ajax({
              url:'',
              type:'post',
               
              // 第一种方式 利用标签查找获取页面上的随机字符串               
              data:{"username":'ricky', 'csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()},                success:function (){
                }
            })
      })
</script>
</body>第二种:
<body> 
<button id="d1">ajax请求</button>    
<script>
        $('#d1').click(function (){
            $.ajax({
                url:'',
                type:'post',
               
        // 第二种方式 利用模板语法提供的快捷书写            
        data:{"username":'ricky', 'csrfmiddlewaretoken':'{{ csrf_token
}}'},           success:function (){
                }
            })
        })
</script>
</body>第三种:通用
配置static静态配置文件:
STATIC_URL
= '/static/'STATICFILES_DIRS
= [    os.path.join(BASE_DIR, 'static')
]自定义js文件名:
代码为官方代码:
// 写一个getCookie方法
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 csrftoken = getCookie('csrftoken');
// 使用$.ajaxSetup()方法为ajax请求统一设置
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", csrftoken);
    }
  }
});导入上述文件,需要先导入JQuery,基于JQuery实现
<body>
  
<button id="d1">ajax请求</button>     
{% load static %}
 <script src="{% static'js/mysetup.js' %}"></script>
<script>
        $('#d1').click(function (){
            $.ajax({
                url:'',
                type:'post',
               
                // 第三种 通用方式 己写一个getCookie方法,然后使用$.ajaxSetup()方法为ajax请求统一设置               
                data:{"username":'ricky'},                
                success:function (){
                }
            })
        })
    </script>
</body>








