Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ajax - JQuery: post FormData AND csrf token together

Is the data:.. line below correct? I want to post the form data AND csrf token to a Django view function.

$('#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
        });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to add your parameters to the FormData object (using append) and as always pass the formdata object alone as the data property.

$('#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
        });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...