簡體   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