表单提交时如何将错误信息传递到页面中,并且保存原来提交数据

曾经何时,你还有我或许都在困惑,如何方便的将验证不通过的表单信息再返回到前台页面,例如我注册一个账号,辛辛苦苦填写了N多项,一个格式验证没有通过,一切都需要充填,虽然Ajax可以解决这个问题,但是我们总不能把所有表单提交都弄成ajax,更何况有若干人就是没事把javascript给禁止了。哎哎,好了解决方案来了,下面以用户登录为例,说说我的解决方案。

服务器端用nodejs实现:

login.html 简单的提交表单

<form action=""  id="loginForm" method="post">

<!--如果提交的信息由用户信息将用户信息填充到表单中-->

<label>手机:</label>
<input type="text"  class="wk_table_input" name="user[mobile]" placeholder="手机号" id="mobile" value="<%if(user){%><%=user.mobile%><%}%>"/><br/>

<label>密码:</label><input type="password"  class="wk_table_input" name="user[pwd]" placeholder="密码" id="pwd" value="<%if(user){%><%=user.pwd%><%}%>"/><br/>

<input type="submit" placeholder=" 登录" class="workteam_public_submit"style="background: #69b754;">
</form>

 <!--如果有错,显示后端返回的错误-->
 <%if(locals.error){%><td class="wpt_td2"><%=error%><%}%>

 

 

function login(req, res, next) {
    //如果用户提交了信息,将信息返回到前端页面
    var user = req.body.user;
    res.render("login", {title:'用户登录', user:user });
};
function loginAction(req, res, next) {
    var user = req.body.user;
    if(!user || !user.mobile || !user.pwd) {
        if (req.xhr) {
            res.json({ret:-1, errMsg:'手机号或密码不能为空'});
        } else {
            res.locals.error = '手机号或密码不能为空';
            login(req, res, next);
        }
    } else { 
        if (user.mobile === '12345678901' && user.pwd === '123456'){
            if (req.xhr){
                res.json({ret:0,errMsg:"",backUrl:""});
            } else {
                res.redirect("/home");
            }
        } else {
            //将错误信息放到locals中,然后调用视图函数
            res.locals.error = "用户名或密码错误";
            login(req, res, next);
        }
    }
    });

‍            res.locals.error = '手机号或密码不能为空'; 


            login(req, res, next);

 

转载于:https://my.oschina.net/wanglihui/blog/299095

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值