【问题标题】:Input type file not serialize jquery输入类型文件不序列化jquery
【发布时间】:2016-02-07 11:23:04
【问题描述】:

我想通过序列化方法使用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&email=kumar%40manish.com

【问题讨论】:

标签: javascript jquery ajax serialization


【解决方案1】:

你应该试试这个:

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/

【讨论】:

    【解决方案2】:

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

    /* 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-29
      • 2018-03-06
      • 2011-08-29
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多