所以我试图使用Ajax为我的Django项目创建一些基本的搜索功能。但是,我一直收到有关CSRF令牌的错误。这是我模板中的javascript:
<script type='text/javascript'>
var csrftoken = Cookies.get('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);
}
}
});
$('#search').keyup(function () {
var search_text = $(this).val();
console.log(search_text);
$.ajax({
type: "POST",
url: "/search/",
data: {
'search_text': search_text,
},
success: function (data) {
console.log('it worked');
},
});
});
</script>
为什么这不起作用?
答案 0 :(得分:1)
尝试将其放入$(document).ready(function(){})
所以这样:
$(document).ready(function(){
var csrftoken = Cookies.get('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);
}
}
});
$('#search').keyup(function () {
var search_text = $(this).val();
console.log(search_text);
$.ajax({
type: "POST",
url: "/search/",
data: {
'search_text': search_text,
},
success: function (data) {
console.log('it worked');
},
});
});
)}