Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 views
in Technique[技术] by (71.8m points)

jquery - Is this an acceptable Ajax action for a CakePHP auto complete?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...