这是 CakePHP 自动完成的可接受的 Ajax 操作吗? [英] Is this an acceptable Ajax action for a CakePHP auto complete?
问题描述
我对 CakePHP 比较陌生,想知道高级用户如何构建他们的 ajax 方法.这段代码的目的是为 jQuery 自动完成创建匹配产品的 JSON 列表.
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();
}
}
只是抛出一个 exit() 感觉有点冒险,但话说回来,我肯定不需要运行任何视图吗?
It feels a bit ballsy to just throw an exit() but then again, I don't need to run any views do I surely?
推荐答案
以下是我过去所做的:
在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
文件夹,里面有对应的视图文件到控制器中的每个动作.使用 .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.
最后,我在 app/views/layouts/json/default.ctp
中有一个布局文件,内容如下:
Lastly, I have a layout file in app/views/layouts/json/default.ctp
with the following:
<?php echo $content_for_layout; ?>
<小时>
例如,http://mydomain.com/items/view.json
映射到 app/views/items/json/view.ctp
,其中包含:
For example, http://mydomain.com/items/view.json
maps to app/views/items/json/view.ctp
which contains:
<?php echo $javascript->object($item); ?>
$item
填充在 app/controllers/items_controller.php
文件中.
不确定这是否有助于增加混淆,但这就是我在 CakePHP 应用程序中使用 JSON 的方式.
Not sure if that helps for adds to the confusion, but that's how I've used JSON in my CakePHP apps.
更新:添加了布局信息.
这篇关于这是 CakePHP 自动完成的可接受的 Ajax 操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!