使用Ajax

时间:2018-05-08 10:18:03

标签: json django

我希望将一些JSON POST数据发送到Django中的URL,以强制实施CSRF保护。我的Ajax看起来像这样:

$.ajax({
        type: "POST",
        url: '/change_ref/'+hash+"/",

        data: {"csrfmiddlewaretoken": "{{ csrf_token }}", "new_ref": newref},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){
            $('#changeref').modal('hide');
            alert('Success!');
        },
        failure: function(errMsg) {
            alert('Failure! ' +errMsg);
        }
    });

我的想法是在后端解析JSON。但是,当我检查传递给服务器的POST数据时,它是空的(如CSRF中间件所示):

enter image description here

当我用JSON.stringify()包装JSON数据时也会发生这种情况。到目前为止我有POST请求工作的唯一方法是使用application/x-www-form-urlencoded Mimetype,但这是不可取的。

我的settings.py很香草。是否需要在Django中进行JSON POST所需的额外步骤,或者此代码是否存在明显错误?

由于

2 个答案:

答案 0 :(得分:1)

您没有发送表单编码数据,因此未使用request.POST。从request.body获取它。

答案 1 :(得分:1)

CSRF令牌应位于HTTP标头中,因此ContentType

也应如此
var csrftoken = Cookies.get('csrftoken');

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
            xhr.setRequestHeader("content-type", "application/json");
        }
    }
});