LoginSignup
2
1

More than 5 years have passed since last update.

cakephp3 で 嬉恥ずかし json

Last updated at Posted at 2017-03-06

・RequestHandlerコンポーネントは使いません
・routes.php 設定も必要ありません

AJAXでJSONを返すコントローラー

yourcontroller.php

//このアクションに対する ajaxperas.ctp はいらない
    public function ajaxperas()
    {
        $this->Peras = TableRegistry::get('Peras');

        $res = $this->Peras->find()
            ->where([
                'user_id' => $this->request['data']['user_id']
            ])
            ->first();

        $this->set([
            'res' => $res,
            '_serialize' => ['res']
        ]);

    }

yomidashimoto.ctp

<script>
    var data = {
        user_id:99
    };

    $.ajax({
        url: "/yourcontroller/ajaxperas/",
        type: "POST",
        dataType: "json",//これが味噌
        data: data
    }).done(function(res){

        console.log(res.res.body);//これでいける。わざわざ解析しなくていい。


    }).fail(function(res){
        alert('error!!!');
    });
</script>

んー!
Ajax で json 取得 と 解析完了。

まとめ
・$.parseJSON は使わない。使うとバグる。
・dataType は json を指定

以上です。
またお会いしましょう。

2
1
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
2
1