JQuery: post FormData AND csrf token together

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

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         }); }); 

回答1:

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         }); }); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!