Javascript 如何将图像附加到序列化?
如何将Javascript 如何将图像附加到序列化?,javascript,jquery,django,ajax,serialization,Javascript,Jquery,Django,Ajax,Serialization,如何将image\u表单添加到Django的表单 form-form.serialize() 图像形式-图像 您可以尝试以下方式: $('#id_submit').click(function(e) { e.preventDefault(); var form = $('form').serialize(); var image_form = $("#id_image").prop("files")[0]; var data = new FormData(); /
image\u表单
添加到Django
的表单
form-form.serialize()
图像形式-图像
您可以尝试以下方式:
$('#id_submit').click(function(e) {
e.preventDefault();
var form = $('form').serialize();
var image_form = $("#id_image").prop("files")[0];
var data = new FormData(); // Creating object of FormData class
data.append("form", form);
data.append("image_form", image_form);
$.ajax({
headers: {'X-CSRFToken': '{{ csrf_token }}' },
type: 'POST',
data: data,
//Options to tell JQuery not to process data or worry about content-type
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
cache: false, // To unable request pages to be cached
success: function (res){}
});
});
serialize()
将返回一个查询字符串(例如name=me&age=99)。因此,如果要向is添加另一个键值对,只需在该字符串中附加&image\u form=123
。随着if form is empty的出现,您将不包括前面的&
,但是现在您编辑它以显示image\u form
是对文件的引用,这将不起作用。是的,在这种情况下如何?可能是序列化数组?
$('#id_submit').click(function(e) {
e.preventDefault();
var form = $('form').serialize();
var image_form = $("#id_image").prop("files")[0];
var data = new FormData(); // Creating object of FormData class
data.append("form", form);
data.append("image_form", image_form);
$.ajax({
headers: {'X-CSRFToken': '{{ csrf_token }}' },
type: 'POST',
data: data,
//Options to tell JQuery not to process data or worry about content-type
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
cache: false, // To unable request pages to be cached
success: function (res){}
});
});