无法将元素附加到FormData

时间:2014-11-20 06:29:00

标签: javascript php jquery ajax

我有一个JavaScript无法将元素追加到我的FormData对象的问题。 这是我的代码

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Files</title>
</head>
<body>
    <h1>File uploading</h1>
<div id="response"></div>
    <form action="index/upload" method="post" enctype="multipart/form-data" name="frmSave">
            <input class="fileUpload" type="file" name="files[]" multiple>          
    </form>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>

Javascript代码如下

$(document).ready(function(){

    $('.fileUpload').change(function(e){
       var formData = new FormData();
       var file = $(this)[0].files;
       formData.append('file', file);
       //console.log(formData); // it's empty!
       // show loading text
       $("#response").html("Uploading file... Please wait");

       // Do upload process, AJAX Post
       $.ajax({
         url: 'index/upload',
         type : "POST",
         data: formData,
         processData : false,
         contentType : false,
         success : function(res) {           
           $("#response").html(res);
           // Show the remove button
         }
       });   

    });

我试图对我的网络服务器(PHP)进行AJAX POST这很完美,但我一直收到异常消息,说我的FormData对象中没有文件。

请帮忙。

谢谢!

更新:

看起来您无法在控制台console.log(formData)中查看formData对象。 POST工作得很好。在PHP方面,我基本上循环遍历$ _FILES。

感谢大家的投入。

2 个答案:

答案 0 :(得分:0)

var formObj = new FormData($('form')[0]); //try like this

我的示例工作示例,

var formObj = new FormData($('form')[0]);
        //formObj.append('test','CodingAnt');
        $.ajax({
          url: 'upload.php',
          data: formObj,
          processData: false,
          contentType: false,
          dataType:'json',
          type: 'POST',
          success: function(data){
            console.log(data.path);
            $('#image_uploaded').attr('src',data.path);
            $('#image_uploaded').show()
          }
        }); 

答案 1 :(得分:0)

使用Jquery serialize()方法

<script>


// The Javascript

$(document).ready(function(){

    $('.fileUpload').change(function(e){

    // show loading text
        $("#response").html("Uploading file... Please wait");

    // Do upload process, AJAX Post
       $.ajax({
         url: 'index/upload',
         type : "POST",
         data: $('form').serialize(),
         processData : false,
         contentType : false,
         success : function(res) {           
           $("#response").html(res);
           // Show the remove button
         }
       });   

    });
</script>
相关问题