CodeIgniter 未內建 IS_AJAX、IS_POST 常數,但可輕鬆透過 $_SERVER 變數自行定義,並在專案中全域複用。本文提供標準定義方式與最佳實踐。
主流 JS 框架會自動發送 X-Requested-With: XMLHttpRequest 標頭:
<?php
// 原生 PHP 判斷
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
<?php
$isPost = strtolower($_SERVER['REQUEST_METHOD']) === 'post';
編輯 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');
<?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);
}
}
}
?>
現代 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 | 預設發送 | 正常運作 |
| 跨域請求 | 預檢請求 OPTIONS | IS_POST 為 false,需單獨處理 OPTIONS |
| 代理伺服器 | 可能移除標頭 | 檢查代理配置保留 X-Requested-With |
在 constants.php 定義常數是最簡潔且全域可用的方式,配合 CI 內建 $this->input->is_ajax_request() 雙重保障,滿足各類專案需求。