使用同一Cake控制器中的两个操作共享一组对象

时间:2014-02-05 21:09:46

标签: php jquery arrays json cakephp

我想用$data数组填充一些值(索引操作)并使用该数组(发送者操作)来创建JSON对象。我想在index.ctp(jQuery)中使用该JSON对象。我尝试使用下面的代码,但它不起作用,我没有收到任何数据(jsonArr)。我认为问题应该在PostsController上,但我找不到解决方案。

PostsController:

<?php 

class PostsController extends AppController {

    public $data = array();

    public function index()
    {

         $this->layout = 'default';

        this->data[] = array
        (
            array(
                "id" => "1",
                "title" => "title1",
                "author" => "author1"
            ),
            array(
                "id" => "2",
                "title" => "title2",
                "author" => "author2"
            ),
            array(
                "id" => "3",
                "title" => "title3",
                "author" => "author3"
            )

        );
    }

    public function sender()
    {
         $this->layout = 'default';

        foreach ($this->data as $i) {
          foreach ($i as $item) {
               $all[] = array(
                "id" => $item['id'],
                "title" => $item['title'],
                "author" => $item['author']
                );
            }
        }

        $this->set("json",json_encode($all));



    }

}

&GT;

index.ctp

<div>
Content  
</div>
<div>
Content
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript"> 

var jsonArr = [];

$.getJSON(plgFcRoot + "posts/sender", function(data) {
                  $.each(data, function(key, val) {
                          jsonArr.push({
                            id : val.id,
                            title : val.title,
                            author: val.author
                          })
                  });


 });

    console.log(jsonArr);


</script>

sender.ctp

<?php

echo $json;


?>

0 个答案:

没有答案