繁体   English   中英

AngularJS $ http.get JSON文件返回未定义

[英]AngularJS $http.get JSON file returns undefined

我正在尝试使用$ 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中的应用

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

  alert(JSON.stringify(data));

结果是一个响应对象(而不是数据本身)。 您可以将数据作为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;
    });
  });

这里的data是一个不是对象的JSON字符串,因此您不能使用data.People ,而只需要将数据传递给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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM