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标签导入此文件即可。

猜你喜欢

转载自www.cnblogs.com/cc123cc/p/10221888.html