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

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 向任何控制器发出请求时 'Cannot Modify Header Information' 错误被写入日志文件但响应没有 error.If 我删除了 set_header()来自构造函数的函数然后 JSON 请求工作正常,没有记录错误。

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

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

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');
}

希望对您有所帮助。