眾所周知前端向后台發送 post 請求時,必須驗證 csrf
,否則會報錯 403 Forbidden
。使用 Django Form 表單可以直接在表單里面添加 {% csrf_token %}
即可,要是通過 Ajax 發送請求又該怎么辦?下面提供三種解決辦法:
<ul id="ddd">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<button id="btn" type="button">Ajax 發送</button>
1. 方式一
<script src="{% static 'js/jquery-3.1.1.js' %}"></script>
<script>
$('#btn').click(function () {
var li_content = [];
$('#ddd').children('li').each(function () {
li_content.push($(this).html());
});
console.log(li_content);
$.ajax({
url: '/webs/test_json/',
type: 'post',
data: {
'li_list': JSON.stringify(li_content),
csrfmiddlewaretoken: '{{ csrf_token }}' // 添加這句
},
success: function (arg) {
console.log(arg);
}
})
})
</script>
2. 方式二
方式二僅在 Django 中適用,因為 {% csrf_token %}
是 Django 的模板語言,它會生成一個隱藏的 input
標簽
<ul id="ddd">
{% csrf_token %} <!--添加這句會生成一個隱藏的 input 標簽,name='csrfmiddlewaretoken'-->
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<button id="btn" type="button">Ajax 發送</button>
<script src="{% static 'js/jquery-3.1.1.js' %}"></script>
<script>
$('#btn').click(function () {
var li_content = [];
$('#ddd').children('li').each(function () {
li_content.push($(this).html());
});
console.log(li_content);
$.ajax({
url: '/webs/test_json/',
type: 'post',
data: {
'li_list': JSON.stringify(li_content),
csrfmiddlewaretoken:$('[name="csrfmiddlewaretoken"]').val() // 添加這句,去獲取 input 的值
},
success: function (arg) {
console.log(arg);
}
})
})
</script>
3. 方式三
因為 cookie
中同樣存在 csrftoken
,所以可以在 js
中獲取:$.cooke("cstftoken")
,並將其添加到請求頭中發送。
1、直接添加請求頭:
$.ajax({
url: '/webs/test_json/',
headers: { "X-CSRFtoken":$.cookie("csrftoken")},
type: 'post',
data: {
'li_list': JSON.stringify(li_content)
},
success: function (arg) {
console.log(arg);
}
})
})
2、如果頁面有多個 Ajax,那么可以設置全局的:
發送請求前會事先執行 $.ajaxSetup()
方法,它會從 cookie
中獲取 csrftoken
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
}
}
});
$.ajax({
url: '/webs/test_json/',
type: 'post',
data: {
'li_list': JSON.stringify(li_content)
},
success: function (arg) {
console.log(arg);
}
})
3、如果想要實現在當 get
方式的時候不需要提交 csrftoken
,當 post
的時候需要,實現這種效果的代碼如下:
<script src="{% static 'js/jquery-3.1.1.js' %}"></script>
<script type="text/javascript" src="/static/js/jquery.cookie.js"></script>
<script>
$('#btn').click(function () {
var li_content = [];
$('#ddd').children('li').each(function () {
li_content.push($(this).html());
});
console.log(li_content);
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
/*
全局Ajax中添加請求頭X-CSRFToken,用於跨過CSRF驗證
*/
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
}
}
});
$.ajax({
url: '/webs/test_json/',
type: 'post',
data: {
'li_list': JSON.stringify(li_content)
},
success: function (arg) {
console.log(arg);
}
})
})
</script>
Tips:一定要導入
jquery.cookie.js
和jquery-3.3.1.js
文件 !!!