首页 > 解决方案 > 在 req.getValidationResult() 方法之后,EJS 页面未呈现/重定向

问题描述

Ajax 请求代码如下:

function validate_referral(e){
    // stop default action
  e.preventDefault();

    const  button = this.children[this.children.length-1];
    //Form Handling with ajax

    $.ajax({
        url      : '/validatereferral',
        method   : 'GET',
        data     :  $(this).serialize(),
        dataType :  'json',

     beforeSend : function(http){
            button.style.opacity = '0.7';
            button.innerText = 'Submitting';
            button.setAttribute("disabled", "true");
        },
    });
}

现在我在数据库中验证代码是否存在,如果存在,我想渲染/重定向到不同的网页。但渲染/重定向失败。任何帮助深表感谢。

router.get('/validatereferral',function(req,res){
    var referralCode = req.body.referralcode;
    if(referralCode == ""){
        data = {msg:"Referral Code is required.",param:"",success:false};
    }else {
        var validation = req.checkBody('referralcode', 'Referral code already exist. Please enter a unique code').isExist_referralcodegen();
            req.getValidationResult()
            .then(function(result) {
                var error = result.array();
                var data;
                if (!(error.length == 0)) {
                    data = {msg: "This is an invalid referral code.", success: false};
                    res.send(data);
                }
                console.log("validgen");
                //res.redirect("http://localhost:3000/signup")
                res.render('signup',{title:"Community Network | Sign Up",header:false,navbar:false});
            })
    }
});

标签: node.jsajaxejs

解决方案


您正在发送 AJAX 请求。在 AJAX 响应中,重定向或渲染不会反映在您的网站上。相反,您的服务器应该响应 url,而客户端必须更改浏览器 url。

$.ajax({
    url      : '/validatereferral',
    method   : 'GET',
    data     :  $(this).serialize(),
    dataType :  'json',
    beforeSend : function(http){
        button.style.opacity = '0.7';
        button.innerText = 'Submitting';
        button.setAttribute("disabled", "true");
    },
}).done(function(data) { 
  location.href = data;
});

在服务器中,

res.send("http://localhost:3000/signup")

推荐阅读