在CakePHP中强制JSON响应

时间:2013-10-18 03:57:26

标签: json rest cakephp

我创建了如下所示的路线:

Router::connect('/:api/:controller/:action/*', array(), array('api'=>'api'));
Router::connect('/:api/:controller', array('action' => 'index'), array('api'=>'api'));
Router::connect('/:api/', array('controller' => 'index', 'action' => 'index'), array('api'=>'api'));

基本上,我希望通过特定端点发出的所有请求都以JSON响应。在上面的例子中,所有使用api前缀的请求。例如:

http://localhost/api/products

应该返回JSON响应而不是HTML。请注意,即使没有定义.json扩展名,它也应该以这种方式工作。

1 个答案:

答案 0 :(得分:8)

所以我在您的控制器中猜测是否设置了api前缀,如果是这样,您将序列化您返回给视图的数据?如果是这样,那么只需添加:

$this->RequestHandler->renderAs($this, 'json');
相关问题