You need to parse the JSON extensions. So in the routes.php file add:
Router::parseExtensions('json');
So, a URL like http://example.com/news/index , now you can access like http://example.com/news/index.json .
To actually return JSON, you need to change the controller methods. You need to set the _serialize key in your action so that your news controller can look like this:
<?php class NewsController extends AppController { public function index() { $news = $this->paginate('News'); $this->set('news', $news); $this->set('_serialize', array('news')); } }
Here are the basics. For POST requests, you want to use the RequestHandler component. Add it to the controller:
<?php class NewsController extends AppController { public $components = array( 'RequestHandler', ... );
And then you can check if the incoming request used the .json extension:
public function add() { if ($this->RequestHandler->extension == 'json') {
source share