Is this an acceptable Ajax action to autoplay CakePHP?

I'm relatively new to CakePHP and wondered how advanced users structure their ajax methods. The purpose of the code is to create a list of compatible JSON products for 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 like you just need to throw away exit (), but then again, I don't need to fire any views, am I sure?

+2
source share
2 answers

Here is what I have done in the past:

In config/routes.phpadd 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');
}

app/views/items app/views/restaurants json . .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.

, , , JSON CakePHP.

UPDATE: ​​ .

+5

ajax ,

<?php echo $content_for_layout ?>

autocomplete.ctp, json.

autocomplete.ctp

<?php echo json_encode($products); ?>
0

Source: https://habr.com/ru/post/1714468/


All Articles