[英]Using jQuery val() to send form data and using FormData to send for data
I tried to send a file using Ajax
post
request using two methods:我尝试使用两种方法使用
Ajax
post
请求发送文件:
Method 1 ( jQuery val()) -方法 1 ( jQuery val()) -
$.ajax({
url: 'somewhere',
method: 'post',
processData: true,
contentType: true,
data:{
'data1':$('#fileinputid').val(), //file input
}
success:function(){
//do something;
}
error:function(){
//do something;
},
});
Method 2- (FormData)方法 2- (FormData)
var formData = new FormData(document.getElementById("form-id"));
$.ajax({
url: 'somewhere',
method:'post',
cache: false,
processData:false,
contentType: false,
data: formData,
success: function(){
//do something for success
},
error: function(){
//do something for error
},
});
Now, Method 2 worked , but Method 1 did not .现在,方法 2有效,但方法 1无效。 What is the reason for that?
这是什么原因?
$('#fileinputid').val()
only gets you the file name , you can not upload a file with that. $('#fileinputid').val()
只为您获取文件名,您不能使用该文件上传文件。
FormData
is capable of creating the whole multipart/formdata request structure that is needed for a file upload. FormData
能够创建文件上传所需的整个 multipart/formdata 请求结构。
data1: formData
you have a typo here. data1: formData
你这里有错字。
It should correctly be data: formData
它应该是正确的
data: formData
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.