从AngularJS中的JSON resp解析$

Parsing $ from JSON resp in AngularJS?

本文关键字:解析 resp JSON AngularJS 中的      更新时间:2023-09-26

如何在$中从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;
});

没有错误响应,在合并时得到一个Object;但不能在其中查询。

$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去掉了所有带有$的密钥。


需要注意的是,我已经尝试过他们的另一个API,但无法获得相同的结果(并且无法包含他们发布日期和质量的有用参数;因为它已损坏)。

它看起来像是一个跨域限制。看看使用$http.jsonp是否适用。

查看YouTube文档中的"将数据API与JavaScript一起使用",其中指出您需要使用alt=json-in-scriptcallback参数。

所以不访问:

$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')

注意差异:

  1. 使用jsonp而不是get
  2. 使用alt=json-in-script而不是alt=json(注意,这可能因API文档而异)
  3. 添加callback=JSON_CALLBACK(注意,根据API文档,这可能有所不同,但AngularJS正在响应中查找JSON_CALLBACK

查看此fiddle以查看工作版本(与基于原始代码的fiddle进行比较)。

还可以查看这篇维基文章,了解更多关于JSONP的信息。