設定/ routes.php:
app_controller.phpでは
Router::parseExtensions('json');
:ビュー/レイアウト/ JSON/default.ctpには
<?php echo $this->Js->object(isset($data) ? $data : array()); ?>
:で
<?php
header('Cache-Control: no-store, no-cache, max-age=0, must-revalidate');
header('Content-Type: application/json');
echo $content_for_layout;
?>
ビュー/ json.ctpで
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);
}
}
コントローラアクションを出力するjson:
$this->set('data', array('foo' => 'bar'));
.json拡張子(www.example.com/posts/view/12.json)を持つアクションを呼び出すたびに、各アクションでレンダリング関数を呼び出す必要なく、jsonオブジェクトが出力されます。