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

标签 php codeigniter content-type exit

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

如果您需要退出死亡,请使用_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 中所使用的那样

关于php - 在 CodeIgniter 输出中使用 Exit 会使内容类型 header 变为 text/html 而不是定义的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39170041/

相关文章:

php - 从逻辑上考虑数据库结构 : Adding 'tags' to things users post - A seperate table or. ..?

php - laravel 在循环中附加 wheres 以执行 AND 过滤

php - 使用php对sql表执行操作

php - 遇到 PHP 错误 严重性 : Core Warning Message: Module 'ffmpeg' already loaded Filename: Unknown Line Number: 0 Backtrace

php - 如何从此结果集中求和和计数?

spring - 为什么 spring 会覆盖 header 中的 Content-Type?

php - MySQL 准备与 PHP mysqli 准备

PHP_CodeSniffer 缺少 Zend 标准?

http - HTTP header (Content-Type 等)是否区分大小写?

drupal - 在 Drupal 中向节点添加强制预览并更改提交按钮值?