为 CakePHP 发送正确的 JSON 内容类型

时间:2023-01-18
本文介绍了为 CakePHP 发送正确的 JSON 内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在我的 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 内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何最好地将 CakePHP 日期选择器表单数据转换为 PHP DateTime 对象? 下一篇:CakePHP:致命错误:允许的内存大小为 536870912 字节已用完(尝试分配 52 字节)

相关文章

最新文章