JQuery:将FormData和csrf标记一起发布

时间:2013-05-26 17:44:50

标签: jquery ajax django

下面的data:..行是否正确?我想将表单数据AND csrf标记发布到Django视图函数。

$('#file-upload').on('change', function () {
    var currentpath = window.location.pathname;
    var formData = new FormData($('form')[0]);
    $.ajax({
            url: currentpath,  //server script to process data
            type: 'POST',
            data: {formData, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
            cache: false,
            contentType: false,
            processData: false
        });
});

1 个答案:

答案 0 :(得分:12)

您必须将您的参数添加到FormData对象(使用append)并始终将formdata对象单独作为data属性传递。

$('#id_image').on('change', function () {
    var currentpath = window.location.pathname;
    var formData = new FormData($('form')[0]);
    formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    $.ajax({
            url: currentpath,  //server script to process data
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false
        });
});