ajax获取django的csrf_token

时间:2022-02-14 15:47:28

'''

方法一:

data: {

'teamid': teamid,

csrfmiddlewaretoken: '{{ csrf_token }}'

//data: {name: 'john', csrfmiddlewaretoken: '{{ csrf_token }}'},

}

方法二:

//获取csrftoken

 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;

}

function csrfSafeMethod(method) {

// these HTTP methods do not require CSRF protection

return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));

}

$.ajaxSetup({

beforeSend: function(xhr, settings) {

var csrftoken = getCookie('csrftoken');

if (!csrfSafeMethod(settings.type) && !this.crossDomain) {

xhr.setRequestHeader("X-CSRFToken", csrftoken);

}

}

});

'''

tonado的:

//获取cookie

function get_cookie(name) {

var xsrf_cookies = document.cookie.match("\b" + name + "=([^;]*)\b");

return xsrf_cookies[1]

}

$.ajax({

'url': '/account/login/',

'type': 'post',

'data': {

'name': $('#name').val(),

'password': $('#password').val(),

// 'code': $('#code').val(),

'captcha': $('#captcha').val(),

'remember': remember

},

// 'headers':{

// // "X-XSRFTOKEN":get_cookie("_xsrf")

// "X-XSRFTOKEN"