前提
- CakePHP 2.x
CakePHPでjson/jsonpを返すAPIをさくっと作る。
routes.php
// hoge.json なURLを有効にする
Router::parseExtensions('json');
ApiController.php
<?php
App::uses('AppController', 'Controller');
class ApiController extends AppController {
public $uses = array('Post');
// RequestHandlerコンポーネントを使用
public $components = array('RequestHandler');
public function search() {
$this->set(array('Posts'), $this->Post->find('all'));
$this->set(array(
'_serialize' => array('Posts'),
'_jsonp' => true
));
}
}
これだけ。
- JSON版URL : http://example.com/api/search.json
- JSONP版URL : http://example.com/api/search.json?callback=hoge
?callback= のクエリパラメータを付与すれば勝手にJSONP形式にしてくれる。