第一种方式
Ajax提交form表单数据,可以在data属性中添加csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val()来通过csrf认证
HTML中
<form action="" method="post">
{% csrf_token %}
username: <input type="text" name="username">
<input type="submit" value="提交">
</form>
js中
$(".btn").click(function () {
$.ajax({
url:'',
type:'post',
data:{"a":1, csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val()},
data:{'a':1},
success:function () {
}
})
})
第二种方式
Ajax提交数据时,通过模版变量从后端获取csrf令牌,
# 不过只适用与前后端混合项目,前后端分离项目是取不到的
js中
$(".btn").click(function () {
$.ajax({
url:'',
type:'post',
data:{"a":1, csrfmiddlewaretoken:'{{ csrf_token }}'},
data:{'a':1},
success:function () {
}
})
})
第三种方式
通过官方给的参考导入数据,只要JavaScript中导入了,Ajax提交数据就不用考虑csrf认证
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;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});