简体   繁体   English

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

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

I am trying to get data from a JSON file to display in my AngularJS app using $http.get(...). 我正在尝试使用$ http.get(...)从JSON文件获取数据以显示在AngularJS应用中。 When I run an alert with JSON.stringify, the alert says 'undefined'. 当我使用JSON.stringify运行警报时,警报显示“未定义”。 Here is my code: 这是我的代码:

JS 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 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"
  ]
}
]
}

What am I missing? 我想念什么?

Update: Here is my app in Plunker 更新:这是我在Plunker中的应用

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

  alert(JSON.stringify(data));

The result is a response object (not the data itself). 结果是一个响应对象(而不是数据本身)。 You can access the data as response.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;
    });
  });

Here data is a JSON string not object, so you can not use data.People , instead you just need to pass data to JSON.parse . 这里的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;
    });
});

I checked with your json string and works using following code. 我检查了您的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