2015-04-12 132 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); 
    });