我試圖從Stack用戶DannYo的comment here合併一些代碼,但是我的他的代碼版本似乎並沒有運行。每次都會返回錯誤和「beforesend」函數。HTML文件上傳與jQuery/Ajax不工作
HTML
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file">
<input type="email" id="sender" name="sender" required>
<input type="email" id="receiver" name="receiver" required>
<input type="text" id="message" name="message">
<button id="send" class="button">Send it</button>
</form>
的JavaScript
$("form").on("submit", function() {
var formData = new FormData($('form')[0]);
$.ajax({
url: 'upload.php', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
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;
},
//Ajax events
beforeSend: function() { console.log("before send function works"); },
success: function(e) {
console.log(e);
},
error: function() { console.log("error function works"); },
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
return false;
});
PHP
出於測試目的,upload.php
文件只有<?php echo "success"; ?>
使用Chrome的網絡開發者工具,我沒有看到我的文件被傳輸到任何地方。有人在我的代碼中看到一個明顯的漏洞?謝謝
'每次都會返回錯誤和「beforesend」函數。「您給出了什麼錯誤? – 2012-07-31 13:38:16
控制檯日誌只是打印我在錯誤函數中指定的內容:「error function works」 – izolate 2012-07-31 13:40:14