2012-07-31 90 views
0

我試圖從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的網絡開發者工具,我沒有看到我的文件被傳輸到任何地方。有人在我的代碼中看到一個明顯的漏洞?謝謝

+0

'每次都會返回錯誤和「beforesend」函數。「您給出了什麼錯誤? – 2012-07-31 13:38:16

+0

控制檯日誌只是打印我在錯誤函數中指定的內容:「error function works」 – izolate 2012-07-31 13:40:14

回答

1

如果你的錯誤函數被調用,那麼答案很可能在其結果中。請檢查顯示的是什麼錯誤error function works你不好嗎。

error: function(xhr, status, error) { 
    alert(xhr.responseText); 
    // OR 
    alert(status + " : " + error); 
} 

編輯:另外需要注意的,我相信你需要處理的文件,您要上傳保存。 T his tutorial for uploading files in php可能有用。

+0

我同意我的錯誤函數是愚蠢的。使用你給我的那個,它只是刷新頁面,但沒有顯示在控制檯之前:'未捕獲的類型錯誤:不能準備好屬性'消息'未定義' – izolate 2012-07-31 13:53:51

+1

@muppethead這很有趣。我用我以前做過的其他事情更新了我的答案。 – 2012-07-31 13:56:32

+0

啊哈!是的,你的編輯證明是有幫助的該錯誤說'progressHandlingFunction'沒有被定義。所以,我添加了進度處理函數,現在窗體不返回錯誤函數。但相反,我得到一個500內部服務器錯誤。那是因爲我在MAMP本地工作嗎? – izolate 2012-07-31 14:01:43