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