这是一个CakePHP的自动完成一个可以接受的阿贾克斯行动? [英] Is this an acceptable Ajax action for a CakePHP auto complete?
问题描述
我是比较新的CakePHP的,并想知道高级用户如何构建自己的AJAX方法。 code此的目的是创建相匹配的产品的JSON列表jQuery的自动完成。
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:
在的config / routes.php文件
,添加以下内容:
Router::mapResources(array('restaurants', 'items'));
Router::parseExtensions('json');
在应用程序/ 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');
}
然后在应用程序/视图/项目
和应用程序/视图/餐厅
,我有一个 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.
最后,我在应用程序/视图/布局/ JSON / default.thtml中
布局文件与以下内容:
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
映射到应用程序/视图/项目/ JSON /视图。 CTP
,其中包含:
<?php echo $javascript->object($item); ?>
$项目
被填充在应用程序/控制器/ items_controller.php
文件。
不知道这有助于为增加了混乱,但是这怎么我用JSON在我的CakePHP应用程序。
Not sure if that helps for adds to the confusion, but that's how I've used JSON in my CakePHP apps.
更新:添加布局信息
这篇关于这是一个CakePHP的自动完成一个可以接受的阿贾克斯行动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!