Uncaught TypeError Illegal invocation when send FormData to ajax

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

I am trying to send a file to the server to do some processing. This is working perfectly fine using the below code:

var formData = new FormData(); formData.append('file', $('#fileUpload')[0].files[0]); options = JSON.stringify(options); // {"key": "value"}  $.ajax({         url: "url",         type: "POST",         data: formData,         processData: false,         contentType: false,         success: function (data) {          },         error: function (msg) {             showMsg("error", msg.statusText + ". Press F12 for details");             console.log(msg);         }     }); 

However, what I am trying to do is not only send the FormData but a json object as well. I am trying to do something like below:

var formData = new FormData(); formData.append('file', $('#fileUpload')[0].files[0]); options = JSON.stringify(options); // {"key": "value"}  $.ajax({         url: "url",         type: "POST",         data: { "formData": formData, "options": options },         //dataType: "json",         //processData: false,         //contentType: false,         success: function (data) {          },         error: function (msg) {             showMsg("error", msg.statusText + ". Press F12 for details");             console.log(msg);         }     }); 

When I do this, I get the error message of Uncaught TypeError Illegal invocation From what i've researched, I cannot find any examples of sending form data like this. Does this need to be restructured of is there some other way to send a json object along with the form data?

回答1:

Appending the JSON object options to the FormData works.

var formData = new FormData(); formData.append('file', $('#fileUpload')[0].files[0]); options = JSON.stringify(options); formData.append('options', options); //append it with the form data and take it apart on the server  $.ajax({     url: "url",     type: "POST",     data: formData,     processData: false,     contentType: false,     success: function (data) {      },     error: function (msg) {         showMsg("error", msg.statusText + ". Press F12 for details");         console.log(msg);     } }); 


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