将FormData发送到Ajax时非法调用TypeError [英] Uncaught TypeError Illegal invocation when send FormData to ajax
问题描述
我正在尝试将文件发送到服务器以进行一些处理.使用下面的代码,这可以很好地工作:
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);
}
});
但是,我想做的不仅是发送FormData,而且还发送json对象.我正在尝试执行以下操作:
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);
}
});
当我这样做时,我收到未捕获的TypeError非法调用的错误消息.根据我的研究,我找不到发送这样的表单数据的任何示例.是否需要进行重组,是否还有其他方法可以将json对象与表单数据一起发送?
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?
推荐答案
将JSON对象options
附加到FormData即可.
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);
}
});
这篇关于将FormData发送到Ajax时非法调用TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!