我试图将一个简单的$ http.get用于.JSON文件,这似乎是找到的,但是当我试图将数据传递到前端时,我在控制台中看到一个错误:
Error: data.unitedkindgom: is undefined
这是我的控制器:
app.controller("CityController", function($scope, $http, cityService) {
$scope.UKCities = [];
cityService.getCityData(function(data) {
$scope.UKCities = data.unitedkindgom.CityInfo;
console.log(data.unitedkindgom.CityInfo);
});
我的JSON:
unitedkindgom: {
"NoCities": 66,
"Balance": 2103,
"Population": 63705000,
"CityInfo": [
{
"CityName": "London",
"CityPopulation": "7825200",
"Facts": {
"SubFact1": "xzy",
"SubFact2": "xzy",
"SubFact3": "xzy",
"SubFact4": "xzy",
"SubFact5": "xzy"
},
},
{
"CityName": "Manchester",
"CityPopulation": "2584241",
"Facts": {
"SubFact1": "abc",
"SubFact2": "abc",
"SubFact3": "abc",
"SubFact4": "abc"
},
}
],
"SubmitInfo": null,
"FormAction": null,
"FormController": null,
}
由于
更新
cityService.getCityData
app.factory('cityService', function($http) {
return {
getCityData: function(done) {
$http.get('/data/city.json')
.success(function(data) { done(data);})
.error(function(error) {
alert('An error has occured');
});
}
}
});
更新
如果我删除$scope.UKCities = data.unitedkindgom.CityInfo;
并将console.log(data.unitedkindgom.CityInfo);
替换为console.log(data);
,我可以在控制台窗口中看到我的所有数据。
如果将console.log(data.unitedkindgom.CityInfo);
替换为console.log(data.unitedkindgom);
,我会在控制台窗口中看到Undefined
。
答案 0 :(得分:1)
使用JSONLint,我发现您的JSON无效,因此无法解析
以下是您数据的有效JSON
{
"unitedkindgom": {
"NoCities": 66,
"Balance": 2103,
"Population": 63705000,
"CityInfo": [
{
"CityName": "London",
"CityPopulation": "7825200",
"Facts": {
"SubFact1": "xzy",
"SubFact2": "xzy",
"SubFact3": "xzy",
"SubFact4": "xzy",
"SubFact5": "xzy"
}
},
{
"CityName": "Manchester",
"CityPopulation": "2584241",
"Facts": {
"SubFact1": "abc",
"SubFact2": "abc",
"SubFact3": "abc",
"SubFact4": "abc"
}
}
],
"SubmitInfo": null,
"FormAction": null,
"FormController": null
}
}
请注意,它完全包含在{ }
中,unitedkindgom
包含在" "
中,此处会删除多余的,
。