{ msg : '返回消息', status : 自定义响应代码, data : '', }
方法1
namespace app\lib; class Response extends \yii\web\Response{ public function alert($message, $code = 1, $data = null){ $this->format = self::FORMAT_JSON; $this->data = [ 'message' => $message, 'code' => $code, 'data' => $data ] return $this; } } //修改response组件的配置后,就可以这样调用了嘛 return Yii::$app->response->alert('余额不足');
方法2
'response' => [ 'on beforeSend' => function($event){ $response = $event->sender; if( $response->format != \yii\web\Response::FORMAT_JSON //没设定format为JSON && is_array($response->data) //数组 ){ $data = $response->data; $response->data = [ 'message' => $data[0], 'code' => isset($data[1]) ? $data[1] : 0, 'data' => isset($data[2]) ? $data[2] : '', ]; $response->format = \yii\web\Response::FORMAT_JSON; } } ], //于是action可以这样用: return ['余额不足']; return ['操作成功!', 0]; return ['搜索结果', 0, $dataList]; return $this->render('xxx'); //此时返回的是string,beforeSend里有is_array的判断,所以不会影响模板的输出
方法3
return Yii::configure(Yii::$app->response, [ 'format' => \yii\web\Response::FORMAT_JSON, 'data' => [ 'message' => '余额不足', 'code' => 1, 'data' => null ], ]);