最近要用yii2把之前老項目重構一下,因為前端打算用vuejs,所以Yii2前端那一套就放棄了,直接給前端傳json數據
控制器代碼:
1 $response = Yii::$app->response; 2 $response->format = \yii\web\Response::FORMAT_JSON; 3 $response->data = $testDataModel->getTestData(); 4 $response->send();
模型代碼:
1 public static function tableName() 2 { 3 return 'user'; 4 } 5 6 public function getTestData() 7 { 8 return TestData::find()->asArray()->all(); //測試數據 9 }
前台直接ajax請求路由地址即可
結果:
1 [{id: "18", username: "allgy", auth_key: "qOj2vJlwm1Uln88HrihrisuVusCy_8_7",…}]