2015-04-20 78 views
0

我有下面的代碼從一個格式的文件傳遞給PHP腳本,然後根據該腳本返回什麼價值,做的東西:麻煩FORMDATA傳遞到AJAX的文件上傳

<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記錄到控制檯,但它看起來是空的。

回答

2

$('img_form')[0] 

選擇所有的元素看起來像

<img_form></img_form> 

,你有沒有?
然而,這

$('#img_form')[0] 

將與ID img_form

<form method="post" id="img_form" enctype="multipart/form-data"> 
選擇元件