思路:当点击登录事件 将表单数据提交到后台控制器,通过接收后台处理后的返回值来判断登录是否成功
1.编写ajax程序
<script type="text/javascript">
$(function(){
$('.btn').click(function(){
url = "{:U('checkLogin')}";
data = $('form').serialize();
$.post(url,data,function(r){
if(r.status==200) {
window.location.href = "{:U('Main/index')}";
}
if(r.status==300){
alert("验证码错误");
}
if(r.status==400){
alert("用户名或密码错误");
}
},'json');
});
});
</script>
2.编写后台方法
function checkLogin(){
//1.获取表单提交的验证码
$codes = I('post.codes');
//2.验证表单提交的验证码和系统生成的是否一样
$v = new \Think\Verify();
if(!$v->check($codes)){
$data['msg']='验证码错误';
$data['status']=300;
$this->ajaxReturn($data);
}
//3.接收用户名和密码
$name = I('post.name');
$pwd = I('post.passwd');
//4.检测用户名和密码是否正确
if(D('User')->check_Login($name,$pwd)){
$data['msg']='登录成功';
$data['status']=200;
$this->ajaxReturn($data);
}else{
$data['msg']='用户名或密码错误';
$data['status']=400;
$this->ajaxReturn($data);
}
}
}
注:以上代码中的200 、300 、400 是个人设定的一个信号,当前端接收到哪个值就能对应出登录结果是什么了。
function(){