在 CodeIgniter 输出中使用 Exit 使内容类型 header 变为 text/html 而不是定义的类型

Using Exit in CodeIgniter output makes the content type header to text/html instead of the defined one

public function jsonExit($array)
{
    $this->con->output->set_content_type('application/json'); // $this->con is get_instance from the constructor
    echo json_encode($array);
}

这段代码以JSON格式正确输出数据。但是当我在函数中包含 exit; 时,内容类型变为 text/html 而不是我定义的 application/json

这是什么原因?我可以用什么来代替 exit?在这种情况下,return 将不起作用,因为它不再只执行此函数 jsonExit。但它会从我调用 jsonExit 函数的地方继续 运行 脚本。我的任务是完全退出。

因为你直接使用了echo

改为使用set_outputDocs here

public function jsonExit($array)
{
    $this->con->output->set_content_type('application/json'); // $this->con is get_instance from the constructor
    $this->con->output->set_output(json_encode($array));
}

如果您需要 exitdie 使用 _displayDocs here

This method is called automatically at the end of script execution, you won’t need to call it manually unless you are aborting script execution using exit() or die() in your code.

public function jsonExit($array)
{
    $this->con->output->set_content_type('application/json'); // $this->con is get_instance from the constructor
    $this->con->output->_display(json_encode($array));
    exit(0);
}

或在example

中使用