ajax发送post请求处理csrf_token的方法


 1 function getCookie(name) {
 2     var cookieValue = null;
 3     if (document.cookie && document.cookie !== '') {
 4         var cookies = document.cookie.split(';');
 5         for (var i = 0; i < cookies.length; i++) {
 6             var cookie = jQuery.trim(cookies[i]);
 7             // Does this cookie string begin with the name we want?
 8             if (cookie.substring(0, name.length + 1) === (name + '=')) {
 9                 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
10                 break;
11             }
12         }
13     }
14     return cookieValue;
15 }
16 var csrftoken = getCookie('csrftoken');
17 
18 function csrfSafeMethod(method) {
19   // these HTTP methods do not require CSRF protection
20   return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
21 }
22 
23 $.ajaxSetup({
24   beforeSend: function (xhr, settings) {
25     if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
26       xhr.setRequestHeader("X-CSRFToken", csrftoken);
27     }
28   }
29 });

 script标签导入此文件即可。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM