使用 jQuery.ajax 提交文件会导致 TypeError
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19722920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submitting a file with jQuery.ajax gives TypeError
提问by user2889070
I am trying to submit a file from a form using jQuery's ajax
method:
我正在尝试使用 jQuery 的ajax
方法从表单提交文件:
var ofile=document.getElementById('image').files[0];
var formdata = new FormData();
formdata.append("image",ofile);
$.ajax({
url:'elements/save_elements',
data:formdata,
type:'POST'
});
This results in the error TypeError: 'append' called on an object that does not implement interface FormData
.
这导致错误TypeError: 'append' called on an object that does not implement interface FormData
。
What causes this error? It doesn't happen on the actual formdata.append
, but inside jQuery.
是什么导致了这个错误?它不会发生在实际的formdata.append
,而是在 jQuery 内部。
回答by Bhau
I was having the same problem with similar code. There's a severe dearth of information about this error, so since the OP didn't elaborate:
我在使用类似的代码时遇到了同样的问题。关于此错误的信息严重缺乏,因此由于 OP 没有详细说明:
With some debugging I realised the error was being thrown by the ajax call in the depths of jquery, not the actual append.
Turns out I'd forgotten to add processData: false, contentType: false
to the ajax request; Doing so fixed the problem.
通过一些调试,我意识到错误是由 jquery 深处的 ajax 调用引发的,而不是实际的追加。原来我忘记添加processData: false, contentType: false
到 ajax 请求中;这样做解决了问题。
回答by Canaan Etai
It works fine when you add the the following to the ajax object:
当您将以下内容添加到 ajax 对象时,它工作正常:
contentType: false,
processData: false,
So it should look like:
所以它应该看起来像:
$.ajax({
url:'elements/save_elements',
data:formdata,
type:'POST',
contentType: false,
processData: false,
});
回答by Radhika Choudhary
Adding these parameter to ajax solve the problem
将这些参数加入ajax即可解决问题
$.ajax({
url: 'upload_ajax.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,