24
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP2系でJSON形式のデータをjQueryが受け取る

Last updated at Posted at 2012-12-26

CakePHP2系を利用して、JSON形式のデータをVIEW側が受け取る方法

環境
CakePHP 2.1.2
PHP 5.3.10


ResponseオブジェクトのbodyにJSONデータをセットしてVIEW側に返却

HogesController.php
class HogesController extends AppController {
     public function hoge() {
          $this->autoRender = false;
          $json = array('json_data'=>array('key01'=>'data01', 'key02'=>'data02'));
          return new CakeResponse(array('body' => json_encode($json)));
     }
}

jQuery.ajax() の dataType を 'json' として受け取るデータを JSON データとして評価
jQuery.parseJSON() を利用して、JSON データをJavaScript オブジェクトに変換

hoge.ctp
<?php
$js = <<< JS
     $(function(){
       var _hoge = function() {
         var json = $.ajax({
              url: 'hoges/hoge',
              async: false,
              type: 'GET',
              dataType: 'json'
         });
         if (json.responseText == '') return true;
         var response = $.parseJSON(json.responseText);
         console.log(response.json_data.key01);
         console.log(response.json_data.key02);
       };
       _hoge();
     });
JS;
echo $this->Html->scriptBlock($js, array('block' => 'script'));
?>
24
23
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
24
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?