繁体   English   中英

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

[英]Ajax Request in Node - Avoid Page Reload

我有一个ajax请求被称为表单提交。 这个想法是在不重新加载页面的情况下保存用户的帐户信息,并向他们提供方便的Flash消息,以使他们知道保存成功。 我没有保存数据的问题,但是在避免在POST上重定向(到包含响应数据的白页)方面确实存在问题。 这是我所拥有的:

在我的翡翠视野中

$("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, e.g.
         // 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的目的。 我想在不重新加载/重定向页面的情况下保存用户的数据,同时让他们知道ajax函数已通过req.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
}

您可以使用简单的按钮单击来代替使用表单提交,这样就不会重新加载页面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM