我试图将内容类型更改为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));
那么,您需要编辑响应标头。
http://kohanaframework.org/3.1/guide/api/Response标题
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();
}
}