使用mvc,ajax
路由
//后台登陆
Route::group('admin', function () {
Route::rule('login', 'admin/Index/login');
//注册
Route::rule('reg', 'admin/Index/reg');
});
ajax
$.ajax({ url: '{:url("admin/index/reg")}', type: 'post', data: $('form').serialize(), dataType: 'json', success: function (res) { if (res.code == 1) { // console.log(11); layer.msg(res.msg, { iocn: 6, time: 2000 }, function () { location.href = res.url; }) } else { layer.msg(res.msg, { iocn: 6, time: 2000 }) } } })
控制器
public function reg() { if (request()->isAjax()) { $data = [ 'username' => input('post.username'), 'pwd' => input('post.pwd'), 'nickname' => input('post.nickname'), 'email' => input('post.email') ]; $res = model('Users')->reg($data); if ($res == 1) { $this->success('注册成功', 'admin/index/login'); } else { $this->error('失败!'); } }; return view('reg'); }
模型
<?php namespace app\common\model; use think\Model; use traits\model\SoftDelete; class Users extends Model { //软删除 use SoftDelete; //注册测试 public function reg($data) { //创建验证器 $val = new \app\common\valid\Admin(); if (!$val->scene('reg')->check($data)) { return $val->getError(); } $res = $this->save($data); if ($res) { return 1; } else { return '注册失败'; } } }
验证器
<?php namespace app\common\valid; use think\Validate; class Admin extends Validate { protected $rule = [ 'username' => 'require', 'pwd' => 'require', 'nickname' => 'require', 'email' => 'require|email', ]; //登陆验证场景 public function login() { return $this->only(['username', 'pwd']); } //注册场景 public function sceneReg() { return $this->only(['username', 'pwd', 'nickname', 'email']); } //验证提示 protected $message = [ 'username.unique' => '栏目名称不能重复', 'username.require' => '用户名必须', 'pwd.require' => '密码必须', ]; }