如何在 AngularJS 中解析 JSON HTTP 响应中的 $
?
尝试在不使用 JQuery 的情况下获取 YouTube 搜索结果:
$http.get('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json&orderby=published')
.success(function (data) {
$scope.video_list = data;
})
.error(function (data) {
$scope.video_list = data;
});
没有错误响应,在控制台时获取一个对象;但无法在其中查询。
$scope.video_list_fun = function () {
$http.get('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json&orderby=published').then(function (response) {
$scope.video_list = response.data;
});
};
同样,也尝试过使用,
链接else
。
$scope.video_list = (httpGet('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json&orderby=published'
)); // HttpGet from http://stackoverflow.com/a/4033310/587021
这有效,但是当我解析它时,例如:使用 JSON.parse
; AngularJS 删除了所有带有 $
的键。
应该注意的是,我已经尝试过 their other API ,但无法获得相同的结果(并且无法包含用于发布日期和质量的有用参数;因为它已损坏)。
最佳答案
看起来像是跨域限制。看看是否使用 $http.jsonp将为您工作。
查看 "Using the Data API with JavaScript" YouTube 文档中指出您需要使用 alt=json-in-script
以及 callback
参数。
因此,不要访问:
$http.get('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json&orderby=published')
您将访问:
$http.jsonp('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json-in-script&orderby=published&callback=JSON_CALLBACK')
注意差异:
- 使用
jsonp
而不是get
- 使用
alt=json-in-script
而不是alt=json
(请注意,这可能会因 API 文档而异) - 添加
callback=JSON_CALLBACK
(请注意,这可能会因 API 文档而有所不同,但 AngularJS 会在响应中查找JSON_CALLBACK
。
Check out this fiddle查看工作版本(与基于原始代码的 this fiddle 进行比较)。
另请查看this wiki有关 JSONP 的更多信息的文章。
关于javascript - 在 AngularJS 中从 JSON 解析 $?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17515249/