繼這篇文章繼續優化https://blog.csdn.net/fangkang7/article/details/83414935php
在上文中這樣的返回碼是不靈活的,咱們在進行下一步優化ajax
1.建立一個message的配置文件,用來存放 錯誤信息thinkphp
<?php return [ 'code' => [ 'SUCCESS' => 1, 'USER_LOGIN_VALIDATE_ERROR' => -1000, 'ERROR_NO_USER' => -1001, 'ERROR_USER_START' => -1002, 'ERROR_PASSWORD' => -1003, 'ERROR_LOGIN_EXCESS_TIME_OUT' => -1005, ], 'info' => [ 1 => '操做成功', -1000 => '用戶登陸校驗不成功', -1001 => '用戶不存在', -1002 => '用戶狀態不對', -1003 => '用戶密碼錯誤', -1005 => '登陸超過規定次數' ] ];
2.建立MessageBehavior鉤子文件(自定義bahavior命令建立看https://blog.csdn.net/fangkang7/article/details/83415607)apache
建立完成須要作配置 app
3.獲取message的信息,爲了方便保存爲常量fetch
<?php namespace app\behavior; use Config; class MessageBehavior { public function run() { $codes = Config::get('message.code'); foreach ($codes as $key => $value) { define($key,$value); } } }
4.在common文件中寫方法,一個是規定返回格式,一個是獲取狀態碼信息優化
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: 咔咔 // +---------------------------------------------------------------------- // 應用公共文件 function ajaxRuturn($code,$data=[]){ $result = ['code' => $code , 'message' => getMessage($code)]; $result = (!empty($data)) ? $result['data'] = $data : $result; return $result; } function getMessage($code){ $info = config('message.info'); return (array_key_exists($code,$info) ? $info[$code] : '操做失敗'); }
5.修改service中的代碼(就是文章開始的那個圖),將狀態碼的常量返回this
<?php namespace app\service; use app\model\user\User; class UserService { public function login($username,$password) { $user = User::where(['user_name'=>$username])->find(); if(!$user){ //用戶名不存在 return ERROR_NO_USER; } if($user->user_status != 1){ // 用戶是否被封 return ERROR_USER_START; } if(!password_verify($password,$user->user_password)){ // 密碼錯誤,登陸失敗 return ERROR_PASSWORD; } //登陸成功 return SUCCESS; } }
6.修改login頁面的方法url
<?php namespace app\admin\controller; use think\Controller; use app\model\user\User; use app\service\UserService; use Request; use Db,Log; class Login extends Controller { private $userService; /** * 初始化 */ public function initialize() { $this->userService = new UserService; } /** * 登陸 * @return \think\Response */ public function login() { if(Request::isPost()){ $username = Request::param('username'); $password = Request::param('password'); return ajaxRuturn($this->userService->login($username,$password)); } return $this->fetch(); } }
響應:spa