当在控制器的构造函数中使用->set_header时,CodeIgniter json请求无法修改头信息


CodeIgniter json requests gives cannot modify header information when output->set_header is used in controller's constructor

我有一个扩展CI_Controller (codeigniter版本2.1.4)的自定义控制器,它具有以下代码

class SM_Restricted extends CI_Controller {
public function __construct()
{
    parent::__construct();
    $this->output->set_header('Last-Modified:'.gmdate('D, d M Y H:i:s').'GMT');
    $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
    $this->output->set_header('Cache-Control: post-check=0, pre-check=0',false);
    $this->output->set_header('Pragma: no-cache');
    if (!$this->session->userdata('isLoggedIn')){
        redirect('login','refresh');
    }
}}

所有其他控制器都是从这个控制器扩展的,除了登录控制器。

所有视图加载正常。但是,当JSON请求任何控制器"不能修改头信息"错误被写入日志文件,但响应没有错误。如果我从构造函数中删除set_header()函数,那么JSON请求就会正常工作,没有错误记录。

为什么会发生这种情况?如何克服这种情况?

您可以检查AJAX请求并相应地加载标题。

if(!$this->input->is_ajax_request())
{
    $this->output->set_header('Last-Modified:'.gmdate('D, d M Y H:i:s').'GMT');
    $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
    $this->output->set_header('Cache-Control: post-check=0, pre-check=0',false);
    $this->output->set_header('Pragma: no-cache');
}