How to get response as json format(application/json) in yii?

后端 未结 8 981
小鲜肉
小鲜肉 2021-01-30 05:08

How to get response as json format(application/json) in yii?

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 05:50

    class JsonController extends CController {
    
        protected $jsonData;
    
        protected function beforeAction($action) {
            ob_clean(); // clear output buffer to avoid rendering anything else
            header('Content-type: application/json'); // set content type header as json
            return parent::beforeAction($action);
        }
    
        protected function afterAction($action) {
            parent::afterAction($action);
            exit(json_encode($this->jsonData)); // exit with rendering json data
        }
    
    }
    
    class ApiController extends JsonController {
    
        public function actionIndex() {
            $this->jsonData = array('test');
        }
    
    }
    

提交回复
热议问题