edo1z blog

プログラミングなどに関するブログです

cakePHP 2.3 JSONビュー

http://book.cakephp.org/2.0/ja/views/json-and-xml-views.html

1.ルーターの設定をする。 Router::parseExtensions('json');

2.コントローラーで、RequestHandlerComponent を有効にする。 public $components = array('RequestHandler');

3.ビューは、専用のビューを使うか、シリアライズするかのどちらか。

/**
 * add method
 * JSONでデータを受け取ってJSONで登録結果を返す
 */
public function add(){
    if ($this->request->is('post')){
        $data = $this->request->input('json_decode');
        if($data){
            //$this->log($data); //debug用
            $this->Customer->create();
            $this->Customer->set($data);
            //バリデーションチェック
            if($this->Customer->validates()){
                if ($this->Customer->save($data)){
                    $this->set('msg', true);
                    $this->set('_serialize', array('msg'));
                }else{
                    $this->set('msg', false);
                    $this->set('_serialize', array('msg'));
                }
            //バリデーションエラー
            }else{
                //$this->log($this->Customer->validationErrors); //debug用
                $this->set('error', $this->Customer->validationErrors);
                $this->set('_serialize', array('error'));
            }
        }
    }
}

4.URLは、パス+.jsonとする。 (例)/users/add.json