在 config/routes.php 中:
Router::parseExtensions('json');
在 app_controller.php 中:
var $components = array('RequestHandler');
var $helpers = array('Js');
function render($action = null, $layout = null, $file = null) {
switch($this->RequestHandler->ext) {
case 'json':
Configure::write('debug', 0);
return parent::render(null, 'default', '/json');
default:
return parent::render($action, $layout, $file);
}
}
在views/json.ctp:
<?php echo $this->Js->object(isset($data) ? $data : array()); ?>
在视图/布局/json/default.ctp:
<?php
header('Cache-Control: no-store, no-cache, max-age=0, must-revalidate');
header('Content-Type: application/json');
echo $content_for_layout;
?>
在你要输出json的控制器动作中:
$this->set('data', array('foo' => 'bar'));
现在每次调用带有 .json 扩展名的操作 (www.example.com/posts/view/12.json) 都会输出一个 json 对象,而无需在每个操作中调用渲染函数。