formData对象无法使用jquery AJAX发布? [英] formData object not working with jquery AJAX post?
问题描述
让我们直接进入代码:
var formData = new FormData();
formData.append('name', dogName);
formData.append('weight', dogWeight);
formData.append('activity', dogActivity);
formData.append('age', dogAge);
formData.append('file', document.getElementById("dogImg").files[0]);
console.log(formData);
这里我将一些字符串和一个文件对象附加到formData对象,以便发送所有信息异步到服务器。
Here I am appending some strings and one file object to the formData object in order to send all the information asynchronous to the server.
之后我有这个jquery ajax请求:
Right after that I have this jquery ajax request :
$.ajax({
type: "POST",
url: "/foodoo/index.php?method=insertNewDog",
data: formData,
processData: false,
contentType: false,
success: function(response){
console.log(response);
},
error: function(){
}
});
所以这里我试图将信息发布到服务器上,在服务器上的php文件我有一个POST的简单print_r所以我看到了什么通过,什么没有。
So here I am trying to POST the info to the server, on the server php file I have a simple print_r of the POST so I see what gets through and what not.
不幸的是我在console.log(数据)中的响应是空的。
Unfortunately my response in the console.log(data) is empty.
此外,如果您在网络选项卡中检查HEADER,则会得到以下空输出:
Also if you check the HEADER in the Network tab you get the following empty output:
成功函数被调用(仅用于澄清)
Success function gets called (just for clarification)
推荐答案
当您通过jQuery发送ajax请求并且想要发送FormData时,您不需要在此FormData上使用 JSON.stringify
。此外,当您发送文件时,内容类型必须是 multipart / form-data
包括 boundry
- 类似这样的的multipart / form-data的; boundary = ---- WebKitFormBoundary0BPm0koKA
When you're sending an ajax request via jQuery and you want to send FormData you don't need to use JSON.stringify
on this FormData. Also when you're sending file the content type must be multipart/form-data
including boundry
- something like this multipart/form-data; boundary=----WebKitFormBoundary0BPm0koKA
所以要通过jQuery ajax发送包含一些文件的FormData,你需要:
So to send FormData including some file via jQuery ajax you need to:
- 将
数据
设置为FormData而不做任何修改。 - 设置
processData
到false
(可以防止jQuery自动将数据转换为查询字符串)。 - 将
contentType
设置为false
(这是必需的,因为否则jQuery会将其设置错误)。 / li>
- Set
data
to the FormData without any modifications. - Set
processData
tofalse
(Lets you prevent jQuery from automatically transforming the data into a query string). - Set the
contentType
tofalse
(This is needed because otherwise jQuery will set it incorrectly).
您的请求应如下所示:
var formData = new FormData();
formData.append('name', dogName);
// ...
formData.append('file', document.getElementById("dogImg").files[0]);
$.ajax({
type: "POST",
url: "/foodoo/index.php?method=insertNewDog",
data: formData,
processData: false,
contentType: false,
success: function(response) {
console.log(response);
},
error: function(errResponse) {
console.log(errResponse);
}
});
这篇关于formData对象无法使用jquery AJAX发布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!