前台后台$.psot交互
前台
{include file='public/header' /} <body class="login-bg"> <div class="login layui-anim layui-anim-up"> <div class="message">x-admin2.0-管理登录</div> <div id="darkbannerwrap"></div> <form> <input name="username" type="text" placeholder="用户名"> <hr class="hr15"> <input name="password" type="password" placeholder="密码"> <p id="infoerror" style="color:red;"></p> <hr class="hr15"> </form> <button id="loginbutton" class="layui-btn layui-btn-lg layui-btn-fluid" onclick="dologin()"><h3>登入</h3></button> </div> <script> function dologin() { var username = $("input[name='username']").val(); var password = $("input[name='password']").val(); if (username == '') { $("#infoerror").text('请填写用户名'); return; } if (password == '') { $("#infoerror").text('请填写密码'); return; } var data = { 'username': username, 'password': password }; $.post("{:url('check')}", data, function (res) { if (res.code == 0) { layer.msg(res.msg); setTimeout("location.href='{:url('home/index')}'", 500); } else if (res.code == 1) { $("#infoerror").text(res.msg); return; } else if (res.code == 2) { $("#infoerror").html(res.msg); return; } }, 'json'); } </script> </body> </html>
后台
<?php namespace app\admin\controller; use app\admin\common\Base; use think\Controller; use think\Request; use think\Db; use think\Session; class Login extends Base { //首页 public function index() { return $this->view->fetch('login'); } /* 验证用户身份*/ public function check() { if($this->alreadyLogin()){ exit(json_encode(array('code'=>2,'msg'=>'用户'.Session::get('admin')['username'].'已登录,<a href='.url('home/index').'>点我跳转到管理界面</a>'))); } $username = trim(input('post.username')); $password = trim(input('post.password')); if(!$username){ exit(json_encode(array('code'=>1,'msg'=>'请填写用户名'))); } if(!$password){ exit(json_encode(array('code'=>1,'msg'=>'请填写密码'))); } //从数据库查询到数组 $data = Db::table('admin')->where('username',$username)->find(); //如果查到为空 if(!$data){ exit(json_encode(array('code'=>1,'msg'=>'用户名不存在'))); } //如果密码匹配 if($data['password'] != md5($username.$password)){ exit(json_encode(array('code'=>1,'msg'=>'密码错误'))); } //验证通过 //设置session Session::set('admin',$data); exit(json_encode(array('code'=>0,'msg'=>'登录成功'))); } /*退出登录*/ public function logout() { //删除session Session::delete('admin'); //执行成功,并返回登录界面 $this->success('注销成功,正在返回···','admin/login/index'); } }