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

Sending correct JSON content type for CakePHP(为 CakePHP 发送正确的 JSON 内容类型)
本文介绍了为 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 内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)