它山之石可以攻玉

键盘上的生活
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

thinkphp3.2用户登录ajax提交验证

Posted on 2017-08-07 11:27  陈达辉  阅读(1850)  评论(0编辑  收藏  举报

html代码

<if condition="!isset($_SESSION['account'])">
        <div class="load lf">
            <p>注册登录</p>
            <div class="userId">
                帐号:<input type="text" placeholder="请输入帐号" value="" name="username" id="username" required>
            </div>
            <div class="userPwd">
                密码:<input type="password" placeholder="请输入密码" value="" name="pwd" id="pwd" required>
            </div>
            <div class="user-choose">
                <label>
                    <input type="checkbox" name="userId">
                    <div class="remember">记住用户名</div>
                </label>
                <a href="#" class="forget">忘记密码</a>
            </div>
            <div class="bottom-choose">
                <button class="submit" id="submit" type="submit"></button>
                <a href="{{:U('register/index')}}" class="register"></a>
            </div>
        </div>
        <else />
        <div class="load lf">
        {{$Think.session.account}} <a href="{{:U('index/loginout')}}">【退出】</a>
        </div>

js代码

<script>
    $(document).ready(function(){
        $("#submit").click(function(){
            var username = $("#username").val();
            var pwd = $("#pwd").val();
            $.post("{{:U('index/login')}}",{username:username,pwd:pwd},function($data){  
                if($data.status == 1){  
                    location.href = $data.url;
                }else{
                    alert($data.info);
                    $('#username').reset();  
                    $('#pwd').reset();
                }     
            }); 
        });
    });
</script>

php代码

    public function login(){
        $username=$_POST['username'];
        $pwd=$_POST['pwd'];
        if($username=='' || $pwd==''){
            $this->ajaxReturn(array('status'=>0,'info'=>'帐号密码不能为空','url'=>''));
        }
        $User = D("User");
        $result=$User->getFields("account='".$username."' and password='".md5($pwd)."'");
        if(empty($result)){
            $this->ajaxReturn(array('status'=>0,'info'=>'登录失败','url'=>''));
        }else{
            session('account',$result['account']);
            $url=U('index/index');
            $this->ajaxReturn(array('status'=>1,'info'=>'登录成功','url'=>$url));
        }
    }
    
    public function loginout(){
        session('account',null);
        $this->redirect('index/index');
    }

model代码

public function getFields($where){
        return $this->where($where)->find();
    }