首页 > 其他分享 >django前后端不分离项目中ajax与csrf问题,加入这个js文件(亲测有效)

django前后端不分离项目中ajax与csrf问题,加入这个js文件(亲测有效)

时间:2024-09-04 09:48:23浏览次数:7  
标签:function cookies name cookieValue django ajax cookie csrf document

function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// 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){
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method))
}

$.ajaxSetup({
beforeSend:function(xhr,settings){
if(!csrfSafeMethod(settings.type)){
xhr.setRequestHeader("X-CSRFTOKEN",getCookie('csrftoken'));
}
}
})

标签:function,cookies,name,cookieValue,django,ajax,cookie,csrf,document
From: https://www.cnblogs.com/yuanyongsheng/p/18395871

相关文章