Submitting a file with jQuery.ajax gives TypeError

泪湿孤枕 提交于 2019-11-27 12:59:51

问题


I am trying to submit a file from a form using jQuery's ajax method:

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.

What causes this error? It doesn't happen on the actual formdata.append, but inside jQuery.


回答1:


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:

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.




回答2:


It works fine when you add the the following to the ajax object:

contentType: false,
processData: false,

So it should look like:

$.ajax({
    url:'elements/save_elements',
    data:formdata,
    type:'POST',
    contentType: false,
    processData: false,
});



回答3:


Adding these parameter to ajax solve the problem

$.ajax({
      url: 'upload_ajax.php',
       type: 'POST',
       data: formData,
       contentType: false,
       processData: false,


来源:https://stackoverflow.com/questions/19722920/submitting-a-file-with-jquery-ajax-gives-typeerror

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