【问题标题】:Where do I put $this->request->headers('Content-Type', 'application/json');我在哪里放 $this->request->headers('Content-Type', 'application/json');
【发布时间】:2011-08-28 13:07:27
【问题描述】:

我正在尝试将 Kohana 中的内容类型更改为 application/json。我把它放在我的控制器中的一个动作中:

$this->request->headers('Content-Type', 'application/json');
$this->content = json_encode($json_data);

但是,请求仍然是 text/html 内容类型。

我应该把$this->request->headers('Content-Type', 'application/json');放在哪里?

【问题讨论】:

    标签: php json kohana content-type kohana-3


    【解决方案1】:

    要详细说明克劳迪奥的答案,是的,您需要设置响应标头,而不是请求,就像这样

    $this->response->headers('Content-Type','application/json');
    

    另外,我不确定您是如何实现控制器的,但它看起来可能是基于

    的模板控制器
    $this->content = json_encode($json_data);
    

    如果您使用的是模板控制器,请确保将 auto_render 设置为 FALSE。

    最后,使用您的 json 数据设置响应正文

    $this->response->body(json_encode($json_data));
    

    【讨论】:

      【解决方案2】:

      嗯,你需要编辑 response 标题。

      http://kohanaframework.org/3.1/guide/api/Response#headers

      【讨论】:

        【解决方案3】:

        OP 询问将它放在哪里。如果您使用的是扩展 Controller_Template 的控制器,就像我一样,我只是将 Andrew Schmid 的代码示例添加到我的基本控制器的 after() 方法中(在 parent::after() 之前)并且效果很好。

        所以:

        Controller_Your_Controller extends Controller_Template {
        
           // Your controller actions
        
           public function after()
           {
               // Set the response content-type here
               $this->response->headers('Content-Type','application/json');
               parent::after();
           }
        }
        

        【讨论】:

          猜你喜欢
          • 2013-04-15
          • 2018-03-11
          • 1970-01-01
          • 2015-08-30
          • 2020-04-23
          • 2020-11-14
          • 1970-01-01
          • 1970-01-01
          • 2016-12-03
          相关资源
          最近更新 更多