首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Yii2 控制器 AJAX 請求處理最佳實踐

     編輯:PHP 綜合知識

Yii2 Controller AJAX 請求處理標準模式

Yii2 控制器處理 AJAX 請求的核心在於 Request::isAjax 判斷與 Response::FORMAT_JSON 回應格式設定。本文提供標準化的 AJAX Action 寫法與前端呼叫範例。

後端 Controller 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' => []];
}

前端 jQuery AJAX 呼叫範例

$.ajax({
    url: '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);
    }
});

進階:統一 AJAX 回應格式

基礎 Controller 封裝

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);
    }
}

CSRF 驗證處理

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 介面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved