2011-08-28 38 views
2

我試圖將內容類型更改爲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');

回答

10

爲了詳細說明克勞迪奧的回答,是的,你需要設置響應頭,而不是請求,像這樣

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

而且,我不知道你是如何實現的控制器,但它看起來像它可能是基於

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

如果您正在使用的模板控制器模板控制器,請確保您設置auto_render爲FALSE。

最後,用你的JSON數據

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

的任擇議定書要求把它放在哪裏設置響應體。如果您正在使用擴展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(); 
    } 
}