ajax登录功能实现

思路:当点击登录事件 将表单数据提交到后台控制器,通过接收后台处理后的返回值来判断登录是否成功

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(){

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值