403(FORBIDDEN)

时间:2015-09-22 09:26:21

标签: javascript python ajax django

我试图发送$ ajax,但我已经得到了它,但是我必须发送带有我的表单的文件,无论是否相同,并不重要。找不到csrf令牌,我收到错误。

我的javascript

    $(document).ready(function() {
        var csrf_token = $('input[name="_token"]').val();

        $.ajaxSetup({
            headers: {
                'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
            }
        });

        // $("body").bind("ajaxSend", function(elm, xhr, s) {
        //     if (s.type == "POST") {
        //         xhr.setRequestHeader('X-CSRF-Token', csrf_token);
        //     }
        // });

        window.getCookie = function(cname) { //window for testing in console
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1);
                if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
            }
            return "";
        };

        function sendPost() {
            var data = $('form').serialize();
            var file = $(document.getElementById('files').files[0]);

            $.ajax({
                type: 'POST',
                url: '/delling_data_objects/document/',
                //data: $('form').serialize(), it's working
                data: file, // its don't
                enctype: 'multipart/form-data',
                headers: window.getCookie('csrftoken')
            });
        };

        $('#submit').on('click', function() {
            sendPost();
        });
    });

我的view.py

def load_files(request):
    form = ApartForm(request.POST)
    import pdb
    pdb.set_trace()
    if form.is_valid():
        form.save()
        file_form = request.POST['file']
        for f in file_form:
            with open(f) as dest:
                for chunk in f.chunks():
                    dest.write(chunk)
    else:
        return HttpResponse('form is not valid')
    return HttpResponse('ok')

1 个答案:

答案 0 :(得分:1)

你没有正确地做到这一点。感觉就像你发送了两次requestHeader一样。(编辑:nevermind没有看到代码的一部分被评论) 根据您的代码,尝试这样的事情:

    function sendPost() {
        var data = $('form').serialize();
        var file = $(document.getElementById('files').files[0]);
        var csrftoken = getCookie("csrftoken");
        $.ajax({
            method: "POST",
            url: '/delling_data_objects/document/',
            data: data,
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            },
            success: function(data) {
                // whatever you want to do
            }
        });
    }


$('#submit').on('click', function() {
    sendPost();
});


var getCookie = function(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== "") {
        var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // 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;
};

var csrfSafeMethod = function (method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};