首页 > 解决方案 > 动态 JSON 不显示但在 AngularJS 中硬编码

问题描述

测试下面的代码时,查询返回正确的数据,但是当我尝试显示返回数据时,它没有显示在我的表中。如果我只是简单地复制返回数据并使 $scope.products 的值显示得很好。动态数据是否需要做一些特别的事情才能使其工作?我是 angularjs 的新手,所以我还在学习。

返回 JSON 数据

{NAME: "21st Amendment Blood Orange IPA", ID: 327},{NAME: "3 Daughters Blonde", ID: 328},{NAME: "90 先令", ID: 329},{NAME: "Avrey Ellie's Brown ", ID: 330},{NAME: "Bed Head Red Ale", ID: 331},{NAME: "Bell's Two Hearted", ID: 332},{NAME: "Berkshire Steel Rail", ID: 333}

angularjs代码

var app = angular.module("root", [])
    app.controller("repeater", ["$scope", "$http", function($scope, $http) {
            $http({method: 'GET', url: 'http://server/angularjs/cfc/sqldata.cfc?method=products'})
        .then(function (response) {
                    var str = '[';
                    for(var i in response.data){
                        str += '{NAME: ' + '"' + response.data[i].NAME + '", ID: ' + response.data[i].ID + '},';                                    
                    }
                    str += ']';
                    //console.log(str);
                    $scope.products = str;
                    //document.write(str);
            });
    }]);

HTML 代码

<div ng-controller="repeater">
    <table border="1" bordercolor="#000000" cellpadding="0" cellspacing="0">
      <thead>
          <tr>
              <td style="font-weight:bold">Index</td>
        <td style="font-weight:bold">Item Id</td>
              <td style="font-weight:bold">Item Name</td>
          </tr>
      </thead>
      <tbody>
          <tr ng-repeat="product in products track by $index" ng-class="{oddRow: $odd}">
              <td>{{$index}}</td>
        <td>{{product.ID}}</td>
              <td>{{product.NAME}}</td>
          </tr>
      </tbody>
  </table>  
</div>

标签: angularjs

解决方案


您不需要重建 JSON 或解析它。您可以像这样直接从响应对象中获取数据:response.data。

看看这个例子:

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

app.controller('postController', ['$scope', '$http', function($scope, $http){
    $scope.data = 'empty';
    $scope.runAJAX = function(){
  $http.get('https://jsonplaceholder.typicode.com/posts').then(function(response){
            $scope.data = response.data;
        }).catch(function(error){
            console.log(error);
        });
    }
}]);
<!DOCTYPE html>
<html lang="en" ng-app="app">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body ng-controller="postController">
    <div>
        <input type="button" value="run" ng-click="runAJAX()" />
    </div>
    <div>
        <table>
            <tr>
                <th>id</th>
            </tr>
            <tr ng-repeat="post in data">
                <td>{{post.id}}</td>
            </tr>
        </table>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="scripts.js"></script>
</body>

</html>


推荐阅读