2013-08-21 37 views
1

我有一個相對簡單的Ajax調用,從一個輸入表單文件上載到服務器:jQuery的AJAX回調文件上傳後,不費一槍

$(function(){ 
     $("form").submit(function(){ 

     var infile = $('#pickedfile'); 

     var actFile = infile[0].files[0]; 

     $.ajax(
     { 
      type: "POST", 
      url: "http://localhost:3000/file_upload", 
      data: [ 
      { 
       file: actFile 
      }], 
      dataType: 'text', 
      success: function() 
      { 
       alert("Data Uploaded"); 
      }, 
      beforeSend: function() 
      { 
       alert("Before Send"); 
       return false; 
      }, 
      error: function() 
      { 
       alert("Error detected"); 
      }, 
      complete: function() 
      { 
       alert("Completed"); 
      } 
     }); 

     }); 

    }); 

而且我成功地收到文件的node.js服務器,並回報:

var express = require('express'), 
    wines = require('./routes/testscripts'); 

var app = express(); 

app.configure(function(){ 
    app.use(express.bodyParser()); 
    app.use(app.router); 
}); 

app.post('/file_upload', function(req, res) { 

    //file should be in req.files.pickedfile 

    // get the temporary location of the file 
     // undefined if file was not uploaded 
     var tmp_path = req.files.pickedfile.path; 

     res.send("Hello, this is server"); 

    }); 
}); 

app.listen(3000); 

該文件上傳成功,並且一切似乎在服務器端正常工作。

但是,在前端,沒有任何警報正在觸發,所以我無法響應來自服務器的任何新數據。是否有一些額外的步驟,我錯過了?

+0

你有沒有試過使用類似Firebug的JS?通過這種方式,您可以確切確定哪條線路導致問題。 –

+0

@DavidStarkey不,我對JavaScript比較陌生,並且不熟悉Firebug。 –

+0

[Firebug](https://getfirebug.com/)適用於Firefox,但許多瀏覽器具有與F12鍵相似的功能(在大多數情況下它們甚至看起來相似)。在「腳本」選項卡下,你可以在JS行上設置一個斷點(比如說,你的AJAX函數的開始)。當該線路運行時,它將停止並讓您逐步完成整個過程。您也可以在觀看變量時觀察變量。對於Web開發人員非常有用的工具 –

回答

0

事實證明,這是兩個問題,一個組合:

1)jQuery的,如在意見中指明,已被中止。

2)因爲jQuery被取消了,所以並沒有阻止關聯的HTML表單正常提交。

這種組合意味着表單將成功提交併接收響應,但由於jQuery代碼默默無力,因此未收到回調。