標籤:list response nbsp class 返回 組件 data orm 響應代碼
{ 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的判斷,所以不會影響模板的輸出
yii2_方便地返回Json