【问题标题】:How to define content-type with Code Igniter REST_Controller如何使用 Code Igniter REST_Controller 定义内容类型
【发布时间】:2012-06-06 03:40:28
【问题描述】:

我正在使用 REST_Controller 扩展 CI_Controller,由于某种原因,我的请求都以 text/html 而不是 json 的内容类型返回。在我的配置中,我将 json 设置为默认格式:

$config['rest_default_format'] = 'json';

我的结果以 JSON 格式返回,但未设置内容类型。任何人都可以帮助我解决我的遗漏吗?

【问题讨论】:

    标签: json codeigniter rest content-type


    【解决方案1】:

    我不确定配置是否设置了格式。但是一个简单的解决方法可能只是使用输出类来设置标题内容类型,例如:

    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode(array('foo' => 'bar')));
    

    (摘自手册:here

    【讨论】:

      【解决方案2】:

      虽然在每个函数中设置 contect_type 会有所帮助,但可以通过在构造函数中设置 this 在控制器级别使其通用。

      public function __construct() {
          parent::__construct();
          ...
          $this->output->set_content_type('application/json');
      }
      

      因此您只需在每个功能级别设置输出

      $this->output->set_output('{"message":"Failure"}');
      

      这对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多