- 使用yii 写接口,默认情况下返回数组会报错,因为默认的响应格式不是json, 要设置这样 \Yii::$app->response->format = json ; 数组才以json格式返回。当然也可以echo json_encode($data); 不过太麻烦。直接用return $data; 更方便一些。但是又不想每个方法里都设置一遍 \Yii::$app->response->format = json ; 有两种方法,第一种方法:在入口文件里application.php的__construct 初始化方法里添加事件,不想改源码的话,可以用一个类继承\yii\web\Application 进行修改。这样就需要吧入口文件里的application类换成自己添加的这个,如下
class Application extends \yii\web\Application { public function __construct(array $config = []) { parent::__construct($config);
$this->response();}
public function response() { \Yii::$app->response->on( \yii\web\Response::EVENT_BEFORE_SEND, function ($event) { /** @var \yii\web\Response $response */ $response = $event->sender; if (is_array($response->data) || is_object($response->data)) { $response->format = \yii\web\Response::FORMAT_JSON; } } ); }
}因为yii每个控制器都需要继承\yii\web\Controller 的,所以第二种方法是在继承的Controller 里添加事件。如下这样:
class WebController extends Controller { public function __construct($id, Module $module, array $config = []) { parent::__construct($id, $module, $config); $this->response(); } public function response() { \Yii::$app->response->on( \yii\web\Response::EVENT_BEFORE_SEND, function ($event) { /** @var \yii\web\Response $response */ $response = $event->sender; if (is_array($response->data) || is_object($response->data)) { $response->format = \yii\web\Response::FORMAT_JSON; } } ); } }