【发布时间】:2015-01-22 12:17:15
【问题描述】:
我正在制作一个天气应用程序,我需要从控制器中获取本地 JSON 文件,然后对数据进行处理。但是,由于某种原因,我无法获得 local $http.get 请求。我该怎么办?
这是我当前的代码:
var weatherApp = angular.module('weatherApp', []);
weatherApp.controller('weatherCtrl', function ($scope, $http) {
$scope.cities = [],
$scope.getCities = (function() {
$http.get('http://localhost:81/Webb/angular projekt/jsons/cities.json')
.success(function(data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
console.log(status);
});
}())
}
这给了我这个错误:
SyntaxError: Unexpected token { angular.js:11598
at Object.parse (native)
at oc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:14:156)
at Yb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:77:190)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:78:50
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:7:302)
at Yc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:78:32)
at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:79:165)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:112:343
at l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:126:193)
at l.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js:123:286)
我也尝试过使用jsons/cities.json,但这会引发此错误:
Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.
向外部资源发出 get 请求可以正常工作,但每当我在本地执行此操作时,似乎都无法正常工作。
我尝试获取的 JSON 文件如下所示:
{"cities": {
{
city: "Stockholm",
latitud: "59",
longitud: "18",
id: "sthlm"
},
{
city: "Göteborg",
latitud: "58",
longitud: "12",
id: "gbg"
},
{
city: "Malmö",
latitud: "55",
longitud: "13",
id: "malmo"
},
{
city: "Umeå",
latitud: "63",
longitud: "20",
id: "umea"
}
}
}
【问题讨论】:
-
您没有传递有效的 URI。 URI 中不能有空格。
-
JSON 格式也错误 - 每个对象的键都需要进行字符串转义,并且城市应该是一个数组。
-
@AndrewCounts 我没有得到同样的结果。
-
@AndrewCounts 原来你可以在其中有一个空格,显然是 JSON 文件错误。我现在可以得到它。
-
@surfitscrollit 你能发表你的评论作为答案吗?我得到了回答该主题的有用答案,但您的评论解决了这个问题。
标签: javascript json angularjs http