节点中的Ajax请求 – 避免页面重新加载

我有一个Ajax请求表单提交调用。 这个想法是保存一个用户的帐户信息,而无需重新加载页面,并给他们一个方便的Flash消息,让他们知道保存是成功的。 我没有保存数据的问题,但我有一个问题,避免在POST上的redirect(与响应数据的白页)。 这是我有:

在我的玉观点

$("form").on("submit", function (e) { e.preventDefault(); // prevent page reload $ajax({ type: "POST", url: '/account', data: $("#accountForm").serialize(), success: function() { // can req.flash even be used here? How might it be? req.flash('info', {msg: 'Your profile has been updated!'}); } } } 

在我的控制器

 exports.postAccount = function(req, res, next) { var userData = req.body; userData.id = req.user.user_id; var updateUserCallback = function(err) { // This is where everything falls apart // Theoretically this should run the success handler in the ajax response res.json(true); // Any response I send changes the view to a white page with the data, eg // res.send(anyData); // Flash also doesn't seem to work, which seems weird... req.flash('info', {msg: 'Your profile has been updated!'}); } // Successfully saves the data, no problems here UserModel.updateUser(userData, updateUserCallback); }; 

通常在updateUserCallback中,我只是呈现帐户视图 ,但是这打破了Ajax的目的。 我想保存用户的数据,而不用页面重载/redirect,同时让他们知道ajax函数通过req.flash (flash模块)成功(或没有)完成。

基本上任何res.send()res.json()调用将数据放入一个普通的白页( res.json()图)。 我想,我从根本上误解了Ajax的工作方式,但我已经跟随Node的jQuery AJAX调用的其他例子,并没有能够避免“白页”的问题。

节点:

 var updateUserCallback = function(err) { return res.send({ message: "Your profile has been updated" }); } 

客户端JS:

 success: function(response) { // can req.flash even be used here? How might it be? // Nope //req.flash('info', {msg: 'Your profile has been updated!'}); $('#someModal').show().html(response.message); // just a sample implementation } 

而不是使用表单提交,你可以使用简单的button点击,使页面不会重新加载。