I want to post a form in django using jquery. I want my form to be able to post a file too. Using form.serialize() as I have read wont pass the contents of the file field. So I read about FormData. But when I use FormData my django view won't recognize it as ajax request. My code (using serialize)
我想使用jquery在django中发布一个表单。我希望我的表单能够发布文件。正如我所读到的那样使用form.serialize()不会传递文件字段的内容。所以我读到了FormData。但是当我使用FormData时,我的django视图不会将其识别为ajax请求。我的代码(使用序列化)
$.ajax({
url:'/customer/create/',
type: form.attr('method'),
contentType:'application/x-www-form-urlencoded;charset=utf-8',
dataType:'json',
data:form.serialize(),
success:onSuccess,
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError + '\n' + xhr.status + '\n' + ajaxOptions);
}
});
and with form data
和表格数据
fd = new FormData(form)
$.ajax({
url:'/customer/create/',
type: form.attr('method'),
contentType:'multipart/form-data',
dataType:'json',
data:fd,
success:onSuccess,
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError + '\n' + xhr.status + '\n' + ajaxOptions);
}
});
Am I missing somethig here? I am not sure this must be the correct contentType. Also mutipart/form-data is set in enctype attribute of the form.
我在这里错过了什么吗?我不确定这必须是正确的contentType。此外,mutipart / form-data在表单的enctype属性中设置。
Also I know about jquery-forms, but don't want to use it yet. I only want this to happen at one form of mine so I don't want to load it in my page. I want to see if there is a solution before going there.
我也知道jquery-forms,但不想使用它。我只希望这种情况发生在我的一种形式,所以我不想在我的页面中加载它。我想在去那儿之前看看是否有解决方案。
3
When using FormData, you need to add processData: false
to your jQuery.ajax options so jQuery won't try processing something it cannot. So do this, and you should be fine:
使用FormData时,需要将processData:false添加到jQuery.ajax选项中,这样jQuery就不会尝试处理它不能处理的东西。这样做,你应该没事:
var form = $('#theForm'),
fd = new FormData(form[0]);
$.ajax({
url: '/customer/create/',
type: form.attr('method'),
contentType: 'multipart/form-data',
dataType: 'json',
data: fd,
processData: false,
success: onSuccess,
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError + '\n' + xhr.status + '\n' + ajaxOptions);
}
});
3
I needed to do something like this:
我需要做这样的事情:
$('#cover_url_file_input').on('change', function(e) {
var file, imgData;
file = this.files[0];
if (file) {
imgData = new FormData();
imgData.append('cover_url', file);
$.ajax({
type: 'POST',
url: $('#cover-form').attr('action'),
data: imgData,
processData: false,
contentType: false,
cache: false,
success: function(result) {
if (result.info === 'OK') {
console.log('OK');
}
}
});
}
});
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2014/01/27/d34cee218a02cc51bb78248024471937.html。