如果(且仅当)您的 Ajax 调用完全与会话无关(也就是说,它不需要登录即可运行,它不需要来自用户的任何会话数据等),您可以提供服务来自单独的 ajax 特定控制器的 Ajax 请求,然后在使用该特定控制器时禁止会话库自动加载。
如果 ajax 调用需要登录用户,那你很不走运。
但是,如果您满足这些条件,请在 application/config/autoload.php 中找到 $autoload['libraries] 部分并使用这个肮脏的 hack:
// Here, an array with the libraries you want/need to be loaded on every controller
$autoload['libraries'] = array('form_validation');
// Dirty hack to avoid loading the session library on controllers that don't use session data and don't require the user to have an active session
$CI =& get_instance();
// uncomment the one that fits you better
// Alternative 1: you only have a single controller that doesn't need the session library
// if ($CI->router->fetch_class() != 'dmz') array_push($autoload['libraries'], 'session');
// END alternative 1
// Alternative 2: you have more than one controller that doesn't need the session library
// if (array_search($CI->router->fetch_class(), array('dmz', 'moredmz')) === false) array_push($autoload['libraries'], 'session');
// END alternative 2
在上面的代码中,dmz 和moredmz 是我的两个假想的控制器名称,需要不加载会话库。只要不使用这些,session 库就会被推入自动加载并因此加载。否则,session 库将被忽略。
我实际上在我的一个站点上运行了此程序,以便允许来自我的负载均衡器的运行状况检查运行(在每个应用程序服务器上每 5 秒一次,来自主负载均衡器及其备份)并填满我的会话表包含无用的数据,并且像魅力一样工作。
不确定您使用的是哪个版本的 CI,但上述代码已在 CI 3.1.11 上测试。
现在,正如您所说的 Ajax 调用需要会话驱动程序,解决此问题的唯一方法是稍微弄乱会话驱动程序本身。在 3.1.11 中,会话驱动程序位于 system/libraries/Session/Session.php 中,您需要更改的部分是构造函数方法的最后部分(从第 160 行开始)。对于这个例子,我假设你的 Ajax 调用由一个名为“Ajax”的特定控制器处理
// This is from line 160 onwards
elseif (isset($_COOKIE[$this->_config['cookie_name']]) && $_COOKIE[$this->_config['cookie_name']] === session_id())
{
$CI =& get_instance();
$new_validity = ($CI->router->fetch_class() !== 'ajax') ? time() + $this->_config['cookie_lifetime'] : $_SESSION['__ci_last_regenerate'] + $this->_config['cookie_lifetime'];
setcookie(
$this->_config['cookie_name'],
session_id(),
(empty($this->_config['cookie_lifetime']) ? 0 : $new_validity),
$this->_config['cookie_path'],
$this->_config['cookie_domain'],
$this->_config['cookie_secure'],
TRUE
);
}
$this->_ci_init_vars();
log_message('info', "Session: Class initialized using '".$this->_driver."' driver.");
简而言之,此示例(尚未对其进行测试,因此请在部署之前进行测试,可能有一两个错字)将首先实例化 CI 核心并从路由器获取控制器名称。如果它是常规控制器,它将确定新的 cookie 有效性为“现在加上配置中的 cookie 有效性”。如果是ajax控制器,cookie有效性将与当前有效性相同(上次重新生成时间加上cookie有效性..必须重申它,因为三元运算符需要它)
之后,setcookie 被修改为使用预先计算的 cookie 有效性,具体取决于 _config['cookie_lifetime'] 的值。