(CSRF令牌丢失或不正确。)在Django中使用AJAX

时间:2018-03-12 05:23:27

标签: javascript jquery ajax django

所以我试图使用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> 

为什么这不起作用?

1 个答案:

答案 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');
        },
    });
});
)}