第一種方式
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);
}
}
});