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

前端 未结 2 1131
萌比男神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:

    <?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.

    0 讨论(0)
  • 2020-12-20 03:16

    I use an ajax layout with nothing in it except

    <?php echo $content_for_layout ?>
    

    Then I just make an autocomplete.ctp view in which I echo the json encoded variable.

    autocomplete.ctp

    <?php echo json_encode($products); ?>
    
    0 讨论(0)
提交回复
热议问题