Here's what I've done in the past:
In config/routes.php
, add the following:
Router::mapResources(array('restaurants', 'items'));
Router::parseExtensions('json');
In app/app_controller.php
:
function beforeFilter() {
if ($this->isApiCall()) {
Configure::write('debug', 0);
}
}
function isApiCall() {
return $this->RequestHandler->isAjax()
|| $this->RequestHandler->isXml()
|| $this->RequestHandler->prefers('json');
}
Then in app/views/items
and app/views/restaurants
, I have a json
folder under each with the corresponding view file to each action in the controller. Requests are made with the .json
extension.
Lastly, I have a layout file in app/views/layouts/json/default.ctp
with the following:
<?php echo $content_for_layout; ?>
For example, http://mydomain.com/items/view.json
maps to app/views/items/json/view.ctp
which contains:
<?php echo $javascript->object($item); ?>
$item
was populated in the app/controllers/items_controller.php
file.
Not sure if that helps for adds to the confusion, but that's how I've used JSON in my CakePHP apps.
UPDATE: Added layout information.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…