問題描述
在我的 CakePHP 應用程序中,我返回 JSON 并針對某些請求退出.一個例子是嘗試訪問 API 以作為 GET 請求登錄:
In my CakePHP app I return JSON and exit for certain requests. An example of this would be trying to access the API for a login as a GET request:
header('Content-Type: application/json');
echo json_encode(array('message'=>'GET request not allowed!'));
exit;
但是,我必須在 echo 前面加上內容類型的前綴,才能將其作為 JSON 發送.否則我在另一端的代碼解釋不同.
However I am having to prefix the echo with the content type in order for it to be sent as JSON. Otherwise my code at the other end interprets it different.
關于如何解決這個問題的任何想法?或者至少改進它.
Any ideas on how to get around this? Or at least improve it.
更新:Cake 2.3.0 版
推薦答案
您可以利用新的 2.x 響應對象:
You can leverage the new 2.x response object:
public function youraction() {
// no view to render
$this->autoRender = false;
$this->response->type('json');
$json = json_encode(array('message'=>'GET request not allowed!'));
$this->response->body($json);
}
參見 http://book.cakephp.org/2.0/en/controllers/request-response.html#cakeresponse
您也可以使用強大的休息功能和 RequestHandlerComponent 來自動實現這一點:http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
Also you could use the powerful rest features and RequestHandlerComponent to achieve this automatically as documented: http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
您只需要允許擴展 json 并將您的操作稱為 /controller/action.json
.然后 cake 將自動使用 JsonView,您只需將數組傳入.視圖類會將其轉換為 JSON 和有效響應.
You just need to allow the extension json and call your action as /controller/action.json
.
Then cake will automatically use the JsonView and you can just pass your array in. It will be made to JSON and a valid response by the view class.
這兩種方式都比您的退出"解決方案更簡潔 - 嘗試對包含 die()/exit() 的代碼進行單元測試.這將悲慘地結束.所以最好一開始就不要在你的代碼中使用它.
Both ways are cleaner than your "exit" solution - try to unit-test code that contains die()/exit(). This will end miserably. So better never use it in your code in the first place.
這篇關于為 CakePHP 發送正確的 JSON 內容類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!