【问题标题】:AngularJS $http.get JSON file returns undefinedAngularJS $http.get JSON 文件返回未定义
【发布时间】:2018-09-21 02:46:26
【问题描述】:

我正在尝试使用 $http.get(...) 从 JSON 文件中获取数据以显示在我的 AngularJS 应用程序中。当我使用 JSON.stringify 运行警报时,警报显示“未定义”。这是我的代码:

JS

var pplApp = angular.module('pplApp', [ 'ngAnimate', 'ngSanitize', 'utilServices' ]);

  pplApp.controller('pplCtrl', function($scope, $http) {
    $http.get('people.json').then(function(data) {
      alert(JSON.stringify(data.People));
      $scope.peoples = data.People;
    });
  });

JSON

{
"People": [
  {
    "name": "Andrew Amernante",
    "rating": 3,
    "img": "http://www.fillmurray.com/200/200",
  "Description": "Gluten­free cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
  "Likes": [
    "Dogs",
    "Long walks on the beach",
    "Chopin",
    "Tacos"
  ],
  "Dislikes": [
    "Birds",
    "Red things",
    "Danish food",
    "Dead Batteries"
  ]
}
]
}

我错过了什么?

更新:这是我在Plunker 中的应用程序

【问题讨论】:

    标签: angularjs json


    【解决方案1】:

    结果是一个响应对象(不是数据本身)。您可以通过response.data 访问数据

    pplApp.controller('pplCtrl', function($scope, $http) {
        $http.get('people.json').then(function(response) {
          alert(JSON.stringify(response.data.People));
          $scope.peoples = response.data.People;
        });
      });
    

    【讨论】:

      【解决方案2】:

      您不应该在 JSON.stringify 中使用点运算符,因为它只是一个字符串,请将其更改为,

        alert(JSON.stringify(data));
      

      【讨论】:

        【解决方案3】:

        这里 data 是 JSON 字符串而不是对象,所以不能使用 data.People,而是您只需将 data 传递给 JSON.parse

        var pplApp = angular.module('pplApp', [ 'ngAnimate', 'ngSanitize', 'utilServices' ]);
          pplApp.controller('pplCtrl', function($scope, $http) {
            $http.get('people.json').then(function(data) {
              var response = JSON.parse(data);
              $scope.peoples = response.People;
            });
        });
        

        我检查了您的 json 字符串并使用以下代码工作。

        var json = '{"People": [{"name": "Andrew Amernante","rating": 3,"img": "http://www.fillmurray.com/200/200","Description": "Gluten­free cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage","Likes": ["Dogs","Long walks on the beach","Chopin","Tacos"],"Dislikes": ["Birds","Red things","Danish food","Dead Batteries"]}]}';
        var response = JSON.parse(json);
        $scope.peoples = response.People;
        

        【讨论】:

        • 感谢您的建议,但是当我设置响应变量然后将数据传递给 JSON.parse 时,我在控制台中收到语法错误:位置 1 处 JSON 中的意外标记 o
        猜你喜欢
        • 1970-01-01
        • 2013-05-31
        • 2014-08-12
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-11
        • 1970-01-01
        相关资源
        最近更新 更多