tp5 ajax控制器返回json,tp5 Api接口 统一结果返回处理

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

2021-04-05

新增,以函数的形式封装要处理的结果。

//成功数据返回function success($msg,$data=''){ $status = [ 'code'=>200, 'msg'=>$msg, 'data'=>$data ]; $response = Response::create($status, 'json'); throw new HttpResponseException($response);}//错误数据返回function error($msg){ $code = 204; if(is_array($msg)){ $code = $msg['code']; $msg = $msg['msg']; } $status = [ 'code'=>$code, 'msg'=>$msg, 'data'=>'' ]; \think\facade\Log::error($status); $response = Response::create($status, 'json'); throw new HttpResponseException($response);}Copy

在需要使用的地方

error('请选择要上传的文件');Copy

2021-03-29

返回信息处理 修改如下,

/** * Trait JsonResponse * @package app\http\response */trait JsonResponse{ /** * 成功时返回的数据 * @param $message * @param $data */ public function jsonSuccessData($data = ''){ return $this->jsonResponse(ApiErrCode::success[0],ApiErrCode::success[1],$data); } /** * 错误时返回的数据 * @param $code * @param $message * @param $data */ public function jsonData($code,$message,$data = ''){ return $this->jsonResponse($code,$message,$data); } /** * 接口返回数据结构 * @param $code * @param $message * @param $data */ private function jsonResponse($code,$message,$data){ $content = [ 'code'=>$code, 'msg'=>$message, 'req_id'=>'', 'data'=>$data ]; return json($content); }}Copy

在需要使用的地方

use JsonResponse;public function getList(){ return $this->jsonSuccessData($result)}