function bindbtn1Event() {
$("#btn1").click(function () {
$.ajax({
url: '/visual/scatter/',
type: "post",
data: $("#form1").serialize(),
dataType: "JSON",
beforeSend: function (xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); // 重点! 注意{{ csrf_token }}必须加上引号!
},
success: function (res) {
if (res.status) {
scatter_vrtg(res.data)
scatter_distance(res.data)
console.log(res.data)
$("#vrtg_string").html(res.data.vrtg_string);
$("#distance_string").html(res.data.distance_string);
}
}
})
})
}
ref:https://www.cnblogs.com/ShankedFlur/p/13611277.html
如果ajax操纵较为频繁,通过写入外部js文件,在post、put、delete等请求需要进行csrf_token验证时,直接引入js文件,但是需注意,此操作的前提是页面中已经通过{{csrf_token}}在cookie中生成了csrf_token字符串,因为该操作的本质和第一个方式一致,都是去页面的cookie中拿到csrf_token的字符串。
step1:引入js文件
<script src="{% static 'js/csrf.js' %}"></script>
step2:js文件内容
/**
* 根据cookie的name获取对应的值
* @param name
* @returns {null}
*/
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) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFTOKEN", getCookie('csrftoken'));
}
}
})