Codeigniter中Ajax请求正常,如何处理普通请求?
解决Codeigniter区分Ajax与普通请求的思路
1. 用Codeigniter内置方法直接判断
Codeigniter的Input类自带is_ajax_request()方法,能直接识别Ajax请求——它会检查请求头里的X-Requested-With: XMLHttpRequest(主流前端Ajax库如jQuery、Axios默认都会携带这个头)。在控制器里直接调用即可:
$this->input->is_ajax_request();
2. 在MY_Controller中做全局统一处理
既然你已经有自定义的MY_Controller,建议在这里把判断逻辑统一封装,避免每个控制器重复写代码:
class MY_Controller extends CI_Controller { public $is_ajax; public function __construct() { parent::__construct(); // 把判断结果存为类属性,子类直接调用 $this->is_ajax = $this->input->is_ajax_request(); } }
3. 控制器内分支处理两种请求
以Welcome控制器的首页方法为例,根据请求类型返回对应内容:
class Welcome extends MY_Controller { public function index() { if ($this->is_ajax) { // Ajax请求:返回JSON格式的接口数据 $response = ['status' => 'ok', 'data' => '专属Ajax内容']; $this->output->set_content_type('application/json')->set_output(json_encode($response)); } else { // 普通浏览器请求:加载完整的页面视图 $this->load->view('common/header'); $this->load->view('home/main'); $this->load->view('common/footer'); } } }
4. 兼容自定义Ajax请求的情况
如果你的前端Ajax请求没有自动携带X-Requested-With头,需要手动添加。比如原生JS的fetch请求:
fetch('/welcome', { method: 'GET', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) .then(res => res.json()) .then(data => console.log(data));
5. 应对代理服务器过滤请求头的场景
部分代理服务器可能会过滤自定义请求头,这时可以用URL参数辅助判断——让前端Ajax请求时带上?ajax=1,控制器里扩展判断逻辑:
$this->is_ajax = $this->input->is_ajax_request() || $this->input->get('ajax') === '1';
内容的提问来源于stack exchange,提问作者Easy Mathematics
相关产品推荐
相关产品推荐

