简体   繁体   中英

Routing to JSON responses in CakePHP

In a CakePhp Project I have an Item Model with its controller:

class ItemsController extends AppController{
  public $components = array('RequestHandler');

  public function data(){
    $items = $this->Item->find('all');
    $this->set('items', $items);
    $this->set('_serialize', array('items'));
  }
}

by specifying in the routes.php :

Router::parseExtensions('json');

I get the JSON response that I want when making a request to /items/data.json

How can I get the JSON response when calling /items/data ? and how can I connect the JSON response in a route. For example if I want /data/items.php to render the same JSON that the /items/data.json request.

Thanks!

I've solved using some methods of RequestHandler in a before filter

public function beforeFilter() {
  parent::beforeFilter();
  $this->RequestHandler->setContent('json');
  $this->RequestHandler->renderAs($this, 'json');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM