I am relatively new to CakePHP and was wondering how advanced users structure their ajax methods. The purpose of code this is to create a JSON list of matched products for a jQuery autocomplete.
function autocomplete() {
$terms = $this->params['url']['q'];
if (!$this->RequestHandler->isAjax()) {
$products = $this->Product->find('list', array(
'conditions' => array(
'Product.name LIKE' => '%'.$terms.'%',
),
'limit' => 7,
'order' => 'Product.name',
'contain' => false
));
exit(json_encode($products)开发者_开发技巧);
} else {
$this->redirect();
}
}
It feels a bit ballsy to just throw an exit() but then again, I don't need to run any views do I surely?
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.
I use an ajax layout with nothing in it except
<?php echo $content_for_layout ?>
Then I just make an autocomplete.ctp view in which I echo the json encoded variable.
autocomplete.ctp
<?php echo json_encode($products); ?>
精彩评论