我对 CakePHP 比较陌生,想知道高级用户如何构建他们的 ajax 方法。代码的目的是为 jQuery 自动完成创建匹配产品的 JSON 列表。
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();
}
}
仅仅抛出 exit() 感觉有点大胆,但话又说回来,我肯定不需要运行任何 View 吗?
最佳答案
这是我过去所做的事情:
在config/routes.php
中,添加以下内容:
Router::mapResources(array('restaurants', 'items'));
Router::parseExtensions('json');
在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');
}
然后在 app/views/items
和 app/views/restaurants
中,我在每个文件夹下都有一个 json
文件夹,其中包含相应的 View 文件 Controller 中的每个操作。请求是使用 .json
扩展名发出的。
最后,我在 app/views/layouts/json/default.ctp
中有一个布局文件,其中包含以下内容:
<?php echo $content_for_layout; ?>
例如,http://mydomain.com/items/view.json
映射到 app/views/items/json/view.ctp
其中包含:
<?php echo $javascript->object($item); ?>
$item
已填充到 app/controllers/items_controller.php
文件中。
不确定这是否会增加困惑,但这就是我在 CakePHP 应用程序中使用 JSON 的方式。
更新:添加了布局信息。
关于jquery - 对于 CakePHP 自动完成来说,这是可接受的 Ajax 操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4975196/