2015-04-12 42 views
0

我在我的應用程序中使用AJAX的前端,並在前端我res.success回從的Node.js /快速應用

$.post('/post', $("#submitform").serialize()) 
       .done(function(res) { 
        //3. Receive the server response, no need to emit an event 
        if (res.success) { 
         //4. Show the updated text 
         console.log('success'); 
        } 
        else { 
         alert(res.error); 
        }}) 
       .fail(function(res) { 
        alert("Server Error: " + res.status + " " + res.statusText); 
       }); 



     return false; 
}); 

我從我的Node.js /快遞發回應用途徑:

res.send(statement); 

然而,res.success不會被觸發,而是我進入alert(res.error)雖然過程執行在後端的罰款。

我在做什麼錯?我應該從我的應用程序的後端發送其他內容,例如res.success

謝謝!

res.status(400).send('Bad Request') 

在您的客戶端腳本使用jQuery Deferred Object

+0

你是什麼'res'對象,有它一個'success'財產?也許這只是來自服務器的數據。 – Magador

+0

其實是的,它就是它的數據從服務器,有啥接收這個數據,看看它是否是表示一切數據行之有效的最佳方法? –

+1

'.done()'是否表示請求已成功?如果是的話,你不需要'res.success' – Magador

回答

1

,因爲你正在使用ExpressJS您的服務器上的NodeJS,你可以在HTTP請求是不正確的發送與服務器的錯誤狀態代碼:您HTTP request is a success

  • deferred.done()被觸發;
  • deferred.fail()如果有clientserver錯誤被觸發;

所以,你應該爲你的代碼中使用:

$.post('/post', $("#submitform").serialize()) 
    .done(function(res) { 
     // Receive the successful server response 
     console.log('success'); 
    }) 
    .fail(function(res) { 
     // Receive the error server response 
     alert("Error: " + res.status + " " + res.statusText); 
    });