简体   繁体   English

使用 jQuery val() 发送表单数据并使用 FormData 发送数据

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM