LoginSignup
50
54

More than 5 years have passed since last update.

CakePHPでjson/jsonpなAPIをサクッと作る

Posted at

前提

  • 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
        ));
    }
}

これだけ。

?callback= のクエリパラメータを付与すれば勝手にJSONP形式にしてくれる。

参照

50
54
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
50
54