首页 > 解决方案 > 插入后无法重定向

问题描述

插入成功后,我想重定向到一个 url:

$(document).ready(function() {
        $("#btn").on("click", function() {
            $.post({
                url:"/track/admin/affecterMenusProfil",
                data:$("#frm").serialize()
            });
        });
    });

router.post("/affecterMenusProfil", function(req, res) {
    var profil = req.body.profil, menus = req.body.menus;
    connexion.query("delete from "+db.getPrefixNomTables()+"profil_menu where profil_id ="+profil, function (errDel, rowsDel) {
        if (errDel) 
            throw errDel;
        async.eachOf(menus, function(menu, position, cb) {
            connexion.query("insert into "+db.getPrefixNomTables()+"profil_menu(menu_id, profil_id) values("+menu+", "+profil+")", function (err, rows) {
                if (err) throw err;
                cb();
            });
        }, function() {
            res.redirect('/track/');
        });
    });
});

但是在运行时没有重定向:插入的页面仍然显示!那么我的代码有什么问题?

标签: node.jsexpress

解决方案


如果您的请求来自 ajax,服务器将不会重定向。

为了重定向,您必须在成功回调的客户端实现重定向逻辑。

$(document).ready(function() {
        $("#btn").on("click", function() {
            $.post({
                url:"/track/admin/affecterMenusProfil",
                data:$("#frm").serialize(), 
                success: function(response) {
                   window.location.href = response.url;
                }
            });
        });
});

router.post("/affecterMenusProfil", function(req, res) {
    var profil = req.body.profil, menus = req.body.menus;
    connexion.query("delete from "+db.getPrefixNomTables()+"profil_menu where profil_id ="+profil, function (errDel, rowsDel) {
        if (errDel) 
            throw errDel;
        async.eachOf(menus, function(menu, position, cb) {
            connexion.query("insert into "+db.getPrefixNomTables()+"profil_menu(menu_id, profil_id) values("+menu+", "+profil+")", function (err, rows) {
                if (err) throw err;
                cb();
            });
        }, function() {
            res.send({url: '/track/'});
        });
    });
});

您必须从服务器发送 URL 并从客户端重定向该 URL,如上所述。我希望它会帮助你。


推荐阅读