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_output
。 Docs 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));
}
如果您需要退出
或死亡
,请使用_display
。 Docs 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 中所使用的那样
关于php - 在 CodeIgniter 输出中使用 Exit 会使内容类型 header 变为 text/html 而不是定义的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39170041/