曾经何时,你还有我或许都在困惑,如何方便的将验证不通过的表单信息再返回到前台页面,例如我注册一个账号,辛辛苦苦填写了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);