为CakePHP发送正确的JSON内容类型 [英] Sending correct JSON content type for CakePHP

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

问题描述

在我的CakePHP应用程序中,我返回JSON并退出某些请求。一个示例是尝试访问作为GET请求的登录API:

  header('Content-Type: application / json'); 
echo json_encode(array('message'=>'GET request not allowed!'));
exit;

但是,我必须在echo的前面加上内容类型,以便将它作为JSON发送。否则我的代码在另一端解释它不同。



有关如何解决这个问题的任何想法?

>解决方案

您可以利用新的2.x响应对象:

  {
//无视图渲染
$ 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



您只需要允许扩展名json,并调用您的操作 /controller/action.json
然后蛋糕将自动使用JsonView,你可以传递你的数组。它将被转换为JSON和视图类的有效响应。



两种方法都比退出解决方案更清洁 - 尝试单元测试包含die()/ exit()的代码。这将结束可悲。所以最好不要在你的代码中使用它。


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;

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.

Update: Cake version 2.3.0

解决方案

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);
}

See http://book.cakephp.org/2.0/en/controllers/request-response.html#cakeresponse

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

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆