【问题标题】:Getting JSON with AngularJS from PHP is not showing on controller使用 AngularJS 从 PHP 获取 JSON 未显示在控制器上
【发布时间】:2016-01-22 14:33:06
【问题描述】:

我正在尝试为 PHP 后端基础应用程序构建基于 AngularJS 的前端。我使用 PHP & MySQL 查询构建 JSON 对象。如果我使用带有ng-init 指令的内联对象,JSON 会正确导出并显示数据。但是当我在控制器上挂载Json.php 文件时,似乎出现了问题,因为我没有看到任何数据。

This is 示例链接,此处控制器位于</body>标签下方。

这是主页

<html ng-app="myApp">
    <head>
        <title></title>
    </head>
    <body>
        <div style="direction: ltr">

        </div>
        <h1>תוצאות שאלון</h1>
        <div class="table-responsive" ng-controller="ContentCtrl">          

        <table class="table" id="results" >
            <thead>
                <tr>
                    <th>id</th>
                    <th>q1</th>
                    <th>q2</th>
                    <th>q3</th>
                    <th>textarea</th>
                    <th>phone</th>
                    <th>name</th>
                </tr>
            </thead>
            <tbody>
<tr ng-repeat="answer in answers.data">

                    <td>{{answer.id}}</td>
                    <td>{{answer.q1}}</td>
                    <td>{{answer.q2}}</td>
                    <td>{{answer.q3}}</td>
                    <td>{{answer.textarea}}</td>
                    <td>{{answer.phone}}</td>
                    <td>{{answer.name}}</td>
</tr>



                <?php/* 
                $table = new Results();
                $table->allrows();
                 */?>
            </tbody>
        </table>
        </div>
       <script src="http://code.jquery.com/jquery.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script type="text/javascript" src="js/js.js"></script>
        <!--<script src="js/controllers.js"></script>-->
        <script type="text/javascript">

这是控制器:

    var myApp = angular.module('myApp', []);

myApp.controller('ContentCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('json.php')

    .success(function(data) {

        $scope.answers = data;

        console.log('test');
    });
}]);

也许模块应该在另一个页面上? 我之前问过this question。也许它可以以某种方式提供帮助。

【问题讨论】:

标签: php angularjs json controller


【解决方案1】:

json.php 文件响应的 JSON 只是一个对象数组。但是您的 ng-repeat 正在迭代 answers.data,这是未定义的。你应该遍历answers,因为那是数组。

<tr ng-repeat="answer in answers">

如果由于某种原因您不想更改 ng-repeat,那么您可以更改控制器,使其将 data 包装在这样的对象中:

$scope.answers = { data: data };

【讨论】:

  • 谢谢。所以你建议我做什么?如何将json.php 中的 JSON 绑定到控制器中的answers.data
  • 为什么不像我展示的那样改变你的ng-repeat
  • 文件中的 ng-repeat 与您所写的完全相同。我看不出文件和您建议的指令之间的区别。我在这里错过了什么?
  • 你是对的,.data 是导致数据不显示的原因
猜你喜欢
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多