我想僅使用jQuery上傳單個文件,然後用處理文件上傳的PHP腳本的輸出替換上載表單。使用jQuery AJAX通過FormData上傳文件
當前我單擊提交後,我收到來自PHP腳本的空白響應。我認爲這是因爲表單數據(文件和上傳輸入)正在被上傳數據覆蓋?
任何幫助解決這個問題,非常感謝!
這裏是我的代碼:
HTML
<div id="container">
<form id="form" enctype="multipart/form-data">
<input name="file" type="file">
<input type="hidden" name="upload">
</form>
<a href="javascript:void(0)" onclick="uploadData($('#form').serialize(), 'upload.php', '#container'); return false;">Upload ></a>
</div>
的JavaScript
function uploadData(data, url, container) {
var formData = new FormData($(data)[0]);
$.ajax({
type: 'POST',
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
$(container).html(response);
},
error: function() {
alert('Error!');
},
});
return false;
};
PHP
if (isset($_POST['upload'])) {
// check the file has been uploaded
if (isset($_FILES['file'])) {
// check if there was an error uploading the file
if ($_FILES['file']['error'] > 0) {
// display error
echo 'Error: ' . $_FILES['file']['error'];
} else {
// move and store file (overwrite if it already exists)
$fileName = '/upload/' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $fileName);
echo 'File uploaded successfully';
}
} else {
die ('Error: No file selected for upload');
}
}
在$ _ POST [「importProducts」],其中是發送從Ajax調用importProducts我看不出來。 – 2013-04-20 06:46:34
哎呀,我剛纔修復了 – cianz 2013-04-20 06:54:28
以便修復問題嗎? – 2013-04-20 07:00:27