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

前端 未结 2 1130
萌比男神i
萌比男神i 2020-12-20 02:09

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

2条回答
  •  佛祖请我去吃肉
    2020-12-20 02:49

    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:

    
    

    For example, http://mydomain.com/items/view.json maps to app/views/items/json/view.ctp which contains:

    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.

提交回复
热议问题