【问题标题】:my cakephp returned json data in array我的 cakephp 在数组中返回了 json 数据
【发布时间】:2015-10-13 06:45:30
【问题描述】:

在 cakephp 中,我有一些编码为 json 的数据(例如:$projects= json_encode($projects);),但我的 php 控制器返回错误的数据模式!我的 json 返回数据在“[]”中,我无法以角度 ng-repeat 访问这种形式的数据以供查看!怎么了?

这是我的 cakephp 控制器的一些部分:

   public function admin_getprojects()
   {

        $projects = $this->Project->find('all',array(
            'contain'=>array('UsersProjects'=>array('User'),
                            'Task')
        ));
        $this->set('projects', $projects);

        $projects= json_encode($projects);
        echo $projects;
        exit();

    }

返回数据: view of json data in json parser... this shouldn't have "[" and "]" at begin and end

【问题讨论】:

  • 实际上它取决于你的数组结构,如果你在数组的第一个元素中有一个键,那么它将返回 "{" 否则将返回 [
  • 固定代码格式。

标签: php json angularjs cakephp


【解决方案1】:

我无法以角度 ng-repeat 访问这种形式的数据以供查看!怎么了?

这不是真的,read the documentation

[] 没有错,而是一个数组,一个对象的集合。 See this question. 我没有看到问题,角度可以处理该数据。 示例参见ng-repeat 的文档

<div ng-init="friends = [
  {name:'John', age:25, gender:'boy'},
  {name:'Jessie', age:30, gender:'girl'},
  {name:'Johanna', age:28, gender:'girl'},
  {name:'Joy', age:15, gender:'girl'},
  {name:'Mary', age:28, gender:'girl'},
  {name:'Peter', age:95, gender:'boy'},
  {name:'Sebastian', age:50, gender:'boy'},
  {name:'Erika', age:27, gender:'girl'},
  {name:'Patrick', age:40, gender:'boy'},
  {name:'Samantha', age:60, gender:'girl'}
]">

看到上面数据中的邪恶[]了吗?它工作得很好:

  I have {{friends.length}} friends. They are:
  <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  <ul class="example-animate-container">
    <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
      [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
    </li>
    <li class="animate-repeat" ng-if="results.length == 0">
      <strong>No results found...</strong>
    </li>
  </ul>
</div>

这可能不会发送正确的标头,也不是写得很好的代码:

$projects= json_encode($projects);
echo $projects;
exit();

阅读该章节 http://book.cakephp.org/3.0/en/views/json-and-xml-views.html 以获得在 CakePHP 中更好的 JSON 实现。

【讨论】:

    【解决方案2】:

    这不是真的,请阅读文档。 [] 没有错,而是一个数组,一个对象的集合。看到这个问题。我没有>看到问题,角度可以处理该数据

    哦,是的!在阅读了 ng-repeat 文档后,我更改了我的 ng-binding 模式,它现在可以工作了 非常感谢:)

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      相关资源
      最近更新 更多