use think\Controller;
use think\Db;
use think\Request;
class User extends Controller
{
public function login(Request $request)//登陆接口
{
header('Access-Control-Allow-Origin:*');
if($request->isPost()){
$data=input('post.');
$result = $this->validate($data,'User');
if(true !== $result){
return json(['status' => 'error','msg' => '用户名或者密码格式不正确!']);
}
$password=substr(md5($data['apassword']),8,16);
$result=Db::name('user')->where('username',$data['ausername'])->where('password',$password)->find();
if($result){
switch ($result['status']) {
case '0':
case '1':
session('userid', $result['id']);
return json(['status' => 'success','msg' => '登陆成功!']);
break;
case '2':
return json(['status' => 'error','msg' => '用户已被禁用,请联系管理员!']);
break;
}
}else{
return json(['status' => 'error','msg' => '用户名或者密码错误!']);
}
}
}
}
<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Request;
class UserCheck extends Controller {
public function _initialize() {
$this->check_login();
}
protected function check_login(){
$userid=session('userid');
if(empty($userid)){
$this->redirect('api/user/login');
}
}
}
<?php
namespace app\api\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'ausername' => 'require|max:20',
'apassword' => 'require|max:20',
];
protected $message = [
'ausername.require' => '请输入用户名',
'ausername.max' => '用户名不能超过20个字符',
'apassword.require' => '请输入密码',
'ausername.require' => '密码不能超过20个字符',
];
}
$("#login").click(function (){
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/tp5/public/index.php/api/user/login" ,//登陆接口路径
data: $('#form1').serialize(),
success: function (result) {
if(result.status=='success'){
window.location.href="index.html";
}else if(result.status=='error'){
alert(result.msg);
return false;
}
},
error : function() {
alert("登陆失败!");
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>首页</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
版权声明:本文为xiaoxinshuaiga原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。