无法将formData传递给AJAX进行文件上传

时间:2015-04-20 22:38:25

标签: php jquery ajax

我有以下代码将文件从表单传递给PHP脚本,然后根据脚本返回的值,执行以下操作:

<script>
function upload_img() {
var formData = new FormData($('img_form')[0]);
console.log(formData);
alert("Hello");
var request = $.ajax({
type: 'POST',
url: 'imgupload.php', 
xhr: function() {  // Custom XMLHttpRequest
        var myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){ // Check if upload property exists
            myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
        }
        return myXhr;
    },
data: formData,
cache: false,
contentType: false,
processData: false
});
alert("Hello3");
request.done(function(data) {
    if (data == 0) {
        $('.image_holder').css("background-image", "url(/images/covers/3.jpg)");  
        alert("image upload succesfull");
    }
    else {
        alert(data);
    }
});
}
</script>
<form method="post" id="img_form" enctype="multipart/form-data">
<input type="file" name="img" id="img" style="position:absolute;top:186px;left:420px">
<input type="submit" value="Upload" onClick=upload_img() class="upload_button" />
</form>

然而,formData似乎没有传递给函数。我已经尝试在创建后将formData记录到控制台,但它似乎是空的。

1 个答案:

答案 0 :(得分:2)

$('img_form')[0]

选择所有看起来像

的元素
<img_form></img_form>

你没有? 但是这

$('#img_form')[0]

将选择ID为img_form

的元素
<form method="post" id="img_form" enctype="multipart/form-data">