使用req.getValidationResult()方法后,EJS页面未呈现/重定向

时间:2018-10-22 04:00:51

标签: node.js ajax 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});
            })
    }
});

1 个答案:

答案 0 :(得分:0)

您正在发送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")