输入类型文件未序列化jquery

时间:2015-11-06 10:27:43

标签: javascript jquery ajax serialization

我想使用序列化方法完成的ajax发送表单数据但输入类型文本和电子邮件在数组中序列化但输入类型文件不在数组中序列化

<form role="form" action="javascript:;" id="myform"  enctype = "multipart/form-data" method = "post">
        <div class="form-group">
          <label for="name">Name:</label>
          <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
        </div>
        <div class="form-group">
          <label for="email">Email:</label>
          <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
        </div>
        <div class="form-group">
          <label for="email">Photo:</label>
          <input type="file" name="userPhoto"  id="userPhoto" class="form-control"  />
        </div>
        <button type="submit" class="btn btn-default submit_add" id="enter">Submit</button>
      </form>

和Ajax代码

$('.submit_add').click(function(e){ 
          e.preventDefault();
          var data = $('#myform').serialize();

          console.log(data); return false;
          $.ajax({ 
              url: '/ajax',
              type: 'POST',
              cache: false, 
              data: data,
              dataType: 'json',
              success: function(data) {
                          if (data.success == true ) {
                            window.location.href  = '/';
                          } else {
                            alert('Error : There is something wrong.');
                          }
                        },
              error: function(jqXHR, textStatus, err){
                   alert('text status '+textStatus+', err '+err);
               }
          })
      }); 

控制台响应

name = manish + prajapati&amp; email = kumar%40manish.com

2 个答案:

答案 0 :(得分:7)

你应该试试这个:

var data = new FormData($("#myform")[0]);

并设置:

processData: false,
contentType: false,

在此处查看更多内容:http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/

答案 1 :(得分:0)

我使用jquery(但是也可以通过香草javascript轻松完成)在文件输入之后创建隐藏文本输入。然后,我将新文本输入的名称设置为与之关联的文件输入的ID,并将其值(选择文件时)设置为文件名。然后可以使用$('form')。serializeArray();并返回与文件输入相对应的隐藏输入的name:value对。

/* The javascript/jquery */

$(document).ready(function(){

  // Dynamically create hidden text inputs for the file inputs' data
  // (create dynamically to avoid having re-write your entire html file)
	$('input:file').each( function(){
    $(this).after('<input type="text" readonly name="' + $(this).attr("id").replace("_", " ") + '" hidden value=""/>');
  });
  
  
  // When the user selects a file to be uploaded...
  $('input:file').change( function(){
  
    // If a file is selected set the text input value as the filename
    if($(this).get(0).files.length !== 0){
      $(this).next('input:text').val($(this).get(0).files[0].name);
    }
  
  });
  
  
  $("form").submit( function(e){
    e.preventDefault();
    //Clear previous data from results div
    $('#results').text("");
    
    // Serialize the form data
    var x = $('form').serializeArray();
    
    // Iterate through the array results and append
    // the data to the results div
    $.each(x, function(i, field) {
      var result  = '<span class="left">' + field.name + ' : </span>';
          result += '<span class="right">' + field.value + '</span><br>';
      $('#results').append(result);
    });
    
  });
  
});
/* The .css */

form {
  display: inline-block;
  left: 0; 
  width: auto;
  max-width: 40%;
  margin-left: 0;
  padding: 0;
}
div.left, div.right, span.left, span.right { 
  display:block; 
  position: relative;
  width: 40%;
}
.rad { font-size: 14px; }
.left { float: left; }
.right { float: right; }

#results { 
  display: inline-block;
  position: relative;
  width: auto;
  min-width: 40%; 
  line-height: 23px;
}
#results .left { 
  color: green; 
  text-align: right;
}
#results .right { 
  color: blue; 
  text-align: left;
  margin-right: 20px;
}

.clearfix { clear: both; }
<!-- The HTML -->

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <form id="myForm">
    <div class="left">
      <label class="right" for="name">Name:</label><br>
      <label class="right" for="gender">Gender:</label><br>
      <label class="right" for="file1">1st Pic:</label><br>
      <label class="right" for="file2">2nd Pic:</label><br>
      <label class="right" for="file3">3rd Pic:</label><br>
      <label class="right" for="file4">4th Pic:</label><br>
    </div>
    
    <div class="right">
      <input class="left" type="text" name="Name" ><br>
      <select class="left" name="Gender">
        <option selected></option>
        <option>Unspecified</option>
        <option>Female</option>
        <option>Male</option>
      </select><br>
      
      <input class="left" type="file" accept="image/*" id="File_1"><br>
      <input class="left" type="file" accept="image/*" id="File_2"><br>
      <input class="left" type="file" accept="image/*" id="File_3"><br>
      <input class="left" type="file" accept="image/*" id="File_4"><br>
    </div>
  </form>
  
  <div id="results" class="right"></div>
  
  <div class="clearfix"></div>
    <input form="myForm" type="submit" id="submit" value="Serialize Form" />
    <input form="myForm" type="reset" value="Reset Form" onClick="this.form.reset()" />
</body>