403禁止使用ajax发送post DJANG

2024-09-28 22:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Ajax将POST数据发送到Django的视图中,但是我有一个错误:403forbidden。在

事实上,我用@csrf_exemptive,但我担心这不是更好的主意。。。在

我的观点:

@csrf_exempt
def myfic(request):
    if request.method == "POST" :
        competences = request.POST.get('theCompetences')
        print("competences : ",competences)
    ...

我的代码JS:

^{pr2}$

更好的解决办法是什么?在

谢谢你的帮助!在


所以我必须加上这个代码:

var csrftoken = $.cookie('csrftoken');

function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

我的函数JS没有改变?在

^{pr2}$

如果是,当我点击提交按钮时,什么都没有发生。。在


Tags: 代码ifsettingsrequestjsajaxfunctionpost