繁体   English   中英

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

[英]Where do I put $this->request->headers('Content-Type', 'application/json');

我正在尝试将内容类型更改为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');

要详细说明Claudio的答案,是的,你需要设置响应头,而不是请求,就像这样

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

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

$this->content = json_encode($json_data);

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

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

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

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

那么,您需要编辑响应标头。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM