我正在尝试使用$ 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": "Glutenfree 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中的应用
答案 0 :(得分:0)
您不应将点运算符与JSON.stringify一起使用,因为它只是一个字符串,请将其更改为
alert(JSON.stringify(data));
答案 1 :(得分:0)
结果是一个响应对象(而不是数据本身)。您可以通过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 :(得分:0)
此处 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": "Glutenfree 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;