【发布时间】:2014-02-17 23:35:36
【问题描述】:
我想使用 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);
}
});
和表单数据
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);
}
});
我在这里错过了什么吗?我不确定这一定是正确的 contentType。在表单的 enctype 属性中还设置了 mutipart/form-data。
我也知道 jquery-forms,但还不想使用它。我只希望这发生在我的一种形式上,所以我不想将它加载到我的页面中。我想在去那里之前看看是否有解决方案。
【问题讨论】:
-
文件不能通过 AJAX 上传,除非你使用一些 jQuery 插件。比如github.com/sigurdga/django-jquery-file-upload
-
文件确实可以使用 FormData 上传,无需插件,如此处所述 - stackoverflow.com/questions/6974684/… 我不确定 Django 无法识别 ajax 请求是什么意思。如果您收到 HTTP 403,可能是因为您的表单中可能没有包含 csrf_token。
-
@warunsl 这就是我所遵循的,只有 request.is_ajax() 在 django 视图中返回 false
-
尝试
contentType: false并将enctype="multipart/form-data"添加到您的 -
@RajeshP needsmorejquery.com