Yii2 控制器處理 AJAX 請求的核心在於 Request::isAjax 判斷與 Response::FORMAT_JSON 回應格式設定。本文提供標準化的 AJAX Action 寫法與前端呼叫範例。
public function actionSample() {
// 1. 驗證 AJAX 請求
if (!Yii::$app->request->isAjax) {
throw new BadRequestHttpException('僅支援 AJAX 請求');
}
// 2. 取得 POST 資料
$data = Yii::$app->request->post();
$searchName = explode(':', $data['searchname'])[0] ?? '';
$searchBy = explode(':', $data['searchby'])[0] ?? '';
// 3. 業務邏輯處理
$search = $this->performSearch($searchName, $searchBy);
// 4. 設定 JSON 回應格式
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
// 5. 回傳結構化資料(自動轉 JSON)
return [
'search' => $search,
'code' => 100, // 自訂業務狀態碼
'message' => 'success', // 可選訊息
];
}
private function performSearch($name, $by) {
// 實際查詢邏輯
return ['results' => []];
}
$.ajax({
url: '= Yii::$app->request->baseUrl . '/controller/sample' ?>',
type: 'post',
dataType: 'json',
data: {
searchname: $("#searchname").val(),
searchby: $("#searchby").val()
},
success: function(response) {
if (response.code === 100) {
console.log('搜尋結果:', response.search);
// 渲染結果到頁面
} else {
alert('錯誤: ' + response.message);
}
},
error: function(xhr, status, error) {
console.error('AJAX 錯誤:', status, error);
}
});
namespace app\controllers;
use yii\web\Controller;
use yii\web\Response;
class ApiController extends Controller {
protected function success($data = [], $message = 'success', $code = 200) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ['code' => $code, 'message' => $message, 'data' => $data];
}
protected function error($message = 'error', $code = 400, $data = []) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ['code' => $code, 'message' => $message, 'data' => $data];
}
}
class SearchController extends ApiController {
public function actionIndex() {
if (!Yii::$app->request->isAjax) return $this->error('非法請求');
$keyword = Yii::$app->request->post('keyword');
$results = SearchService::search($keyword);
return $this->success($results);
}
}
AJAX 請求需攜帶 CSRF Token:
// 全域設定(在 layout 或主 JS)
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
// 或單獨請求
data: {
_csrf: $('meta[name="csrf-token"]').attr('content'),
// 其他資料
}
// Layout 中輸出 CSRF meta
public function actionAjax() {
try {
if (!Yii::$app->request->isAjax) throw new BadRequestHttpException();
$model = new SearchForm();
if (!$model->load(Yii::$app->request->post()) || !$model->validate()) {
return $this->error('參數驗證失敗', 422, $model->errors);
}
$data = Service::process($model);
return $this->success($data);
} catch (\Exception $e) {
Yii::error($e->getMessage(), __METHOD__);
return $this->error('伺服器內部錯誤', 500);
}
}
Yii2 AJAX 處理核心三步驟:驗證 isAjax → 設定 FORMAT_JSON → 回傳陣列自動序列化。封裝統一回應格式、整合 CSRF 防護、標準化異常處理,能構建穩健、可維護的 API 介面。