如何区分php(或codeigniter)中的ajax调用和浏览器请求


how to differentiate ajax call and browser request in php (or codeigniter)?

有没有一种方法可以区分php中的ajax调用和普通浏览器请求(或者特定的codeigner(?

这是我的jquery ajax调用:

$(document).ready(function() {
    $('#container').load('http://localhost/index.php/customer/'); 
});

这是代码点火器中客户控制器的索引方法:

public function index() {
    //if (call == 'ajax request') 
    //  do this if it's an ajax request;
    //else
    //  do that if user directly type the link in the address bar;
    $this->load->view('customer/listview');
}

任何帮助都将不胜感激。谢谢

CodeIgniter方式。。

$this->input->is_ajax_request()
function getIsAjaxRequest()
{
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
}

在某个地方定义这个函数,然后当然像这样使用:

if (getIsAjaxRequest())
// do this
else
// do that

但CodeIgniter中可能已经实现了这样的东西,只是对HTTP_X_REQUESTD_WITH 进行全局搜索

if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {}

应该做你需要做的事。尽管它显然可以像任何其他HTTP头一样伪造,所以不要依赖它来做任何重要的事情。

这是Codeigniter对该功能的实现。

if($this->input->isAjax()) {
        }  

不依赖可能会更改的服务器变量,例如,如果服务器位于反向代理之后,我通过一个javascript函数执行所有AJAX调用,在该函数中我添加了一个POST变量:isajax。然后我使用类似$this->UI->IsAJAX((的东西来检查它,它查找在设置控制器时初始化的变量。

$this->_isAJAX = (empty($_POST['isajax']) ? true : false.