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

CodeIgniter 判斷 AJAX 與 POST 請求的常數定義技巧

     編輯:PHP 綜合知識

CodeIgniter 未內建 IS_AJAX、IS_POST 常數,但可輕鬆透過 $_SERVER 變數自行定義,並在專案中全域複用。本文提供標準定義方式與最佳實踐。

一、核心判斷邏輯

AJAX 請求判斷

主流 JS 框架會自動發送 X-Requested-With: XMLHttpRequest 標頭:

<?php
// 原生 PHP 判斷
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
       && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

POST 請求判斷

<?php
$isPost = strtolower($_SERVER['REQUEST_METHOD']) === 'post';

二、CodeIgniter 專案整合方案

方案 1:配置檔定義常數(推薦)

編輯 application/config/constants.php:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 請求類型判斷常數
 */
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) 
    && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');

define('IS_POST', strtolower($_SERVER['REQUEST_METHOD']) === 'post');
define('IS_GET',  strtolower($_SERVER['REQUEST_METHOD']) === 'get');
define('IS_PUT',  strtolower($_SERVER['REQUEST_METHOD']) === 'put');
define('IS_DELETE', strtolower($_SERVER['REQUEST_METHOD']) === 'delete');

方案 2:Base Controller 載入(動態判斷)

<?php
class MY_Controller extends CI_Controller {
    public function __construct() {
        parent::__construct();
        // 掛載到 Controller 實例,視圖也能存取
        $this->is_ajax = $this->input->is_ajax_request(); // CI 內建方法
        $this->is_post = ($this->input->server('REQUEST_METHOD') === 'POST');
    }
}

注意:CI 3 內建 $this->input->is_ajax_request() 等同上述邏輯,CI 4 則為 $this->request->isAJAX()。

三、控制器中使用範例

<?php
class Api extends CI_Controller {
    public function submit() {
        if (IS_POST) {
            // 統一處理 POST 資料
            $data = $this->input->post();
            
            if (IS_AJAX) {
                // AJAX 請求回傳 JSON
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode(['status' => 'ok', 'data' => $data]));
            } else {
                // 一般表單提交導向頁面
                $this->session->set_flashdata('success', '提交成功');
                redirect('form/success');
            }
        }
    }
    
    public function search() {
        if (IS_AJAX && IS_GET) {
            $keyword = $this->input->get('q');
            $results = $this->model->search($keyword);
            echo json_encode($results);
        }
    }
}
?>

四、進階:支援 Content-Type 判斷

現代 API 常用 application/json 而非表單,需額外判斷:

<?php
define('IS_JSON', (isset($_SERVER['CONTENT_TYPE']) 
    && strpos($_SERVER['CONTENT_TYPE'], 'application/json') === 0)
    || (isset($_SERVER['HTTP_CONTENT_TYPE']) 
    && strpos($_SERVER['HTTP_CONTENT_TYPE'], 'application/json') === 0));

// 獲取 JSON 原始輸入
if (IS_JSON) {
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
}
?>

五、常見陷阱與解決

情境問題解決
jQuery $.ajax預設發送 X-Requested-With正常運作
fetch API不自動發送該標頭手動加入 headers: {'X-Requested-With': 'XMLHttpRequest'}
axios預設發送正常運作
跨域請求預檢請求 OPTIONSIS_POST 為 false,需單獨處理 OPTIONS
代理伺服器可能移除標頭檢查代理配置保留 X-Requested-With

在 constants.php 定義常數是最簡潔且全域可用的方式,配合 CI 內建 $this->input->is_ajax_request() 雙重保障,滿足各類專案需求。

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