【问题标题】:AngularJS issue with getting external JSON获取外部 JSON 的 AngularJS 问题
【发布时间】:2014-09-15 12:01:19
【问题描述】:

好的,我是 AngularJS 的新手,正在尝试从外部 API 获取数据。这样做的最终结果基本上将帮助我理解 angularjs,使用外部数据,以及为我的帐户或我搜索的其他人获取使命召唤幽灵的一些统计数据。

我知道 $http.jsonp 是要走的路,但 API 并不像 CORS 那样真正支持它......我已经解释了这一点。我已经能够使用 jquery 进行测试以确保我可以做到,但我无法用 AngularJS 弄清楚。

我在使用https://stackoverflow.com/a/7910570/1888585https://stackoverflow.com/a/6104416/1888585 中的whateverorigin 和anyorigin 时遇到的一个问题是我收到http 错误500(内部服务器错误)

没有它们,我会收到关于我得到的 json 的错误(这是有效的 json,用 json linter 检查)-> 'Uncaught SyntaxError: Unexpected token :'

这就是我所拥有的:

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body ng-controller="GhostsCtrl">
    <div id="text">
        Data from site: {{getGhostData()}}
        Data from site: {{info}}
    </div>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.js"></script>

    <script>

        var myApp = angular.module('myApp', []);
        var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
        var network = "xbl";

        var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
        var wrapURL = "http://anyorigin.com/get?url="+url+"&callback=?";
        var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
       //-----------
        myApp.service('dataService', function($http) {
           console.log("in service!!");
           this.getData = function() {
               console.log("http fn");
               resp = "test";
               // from here i get the syntax error
               $http.jsonp("http://"+url+"&callback=JSON_CALLBACK")
                       .success(function(data) {
                           console.log("Data gotten");
                           console.log(data.contents.user);
                           resp = "Success";
                       }).error(function(data ) {
                           console.log("error");
                           resp = "error";
                       });
               return resp;
           }
        });


        myApp.controller('GhostsCtrl', function($scope, $http, dataService){
            $scope.info = null;
            $scope.info = dataService.getData();

            $scope.getGhostData = function() {
                // from here I get the 500 error
                delete $http.defaults.headers.common['X-Requested-With'];
                $http.jsonp(wrapURL4).success(function(data) {
                    console.log("success: "+data.contents);
                    $scope.info = data.contents.user;
                }).error(function(data) {
                    console.log("error: " + data);
                });
            }

        });

    </script>
</body>
</html>

对于我的 jquery 代码,它工作得很好:

$.getJSON('http://anyorigin.com/dev/get?url=api.codcp.com/user_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=?', function(data){
        $.each(data.contents.user, function(val, idx) {
            $("#text span").append(val+" ");
        })
        console.log(data.contents.user);
    });

返回的json如下:

{"user":{"profile":{"ucdid":"3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c","gamertag":"xNF6xVENGE","network":"xbl","image":"http://avatar.xboxlive.com/avatar/xNF6xVENGE/avatarpic-l.png","kdr":1.109316019930545,"winr":2.7632311977715878,"kill":14694,"deaths":13246,"wins":992,"losses":359,"hoursPlayed":147.32049180327868,"currentStreak":0,"preferredWeapon":"weapon.iw6_arx160"},"squadMember":{"gamertag":"Erskine","xp":1031872,"background":20,"patchbacking":0,"patch":"patch_590","level":57,"nextLevelXp":1070000,"nextLevel":58,"prevLevel":56,"prevLevelXp":1030000,"progress":0.0468,"prestige":6},"careerHistory":{"blackops2prestige":3,"mw3prestige":6,"nextreadblackops2":1405837382,"nextreadmw3":1405841587,"playedblackops2":true,"playedmw3":true},"accounts":["xbl","ucd"],"clan":{"teamId":34018,"name":"xATFWx","memberCount":24,"tag":"ATFW","motto":"Search & destroy ","mottoBg":22,"motd":"","stats":null,"entitlements":268435448,"cxp":1991990,"kdr":1.5,"winp":74,"chat_token":"a2236f048c2a5ab71473b6765909a7f88b8716782dff8fd7b1f9df43b4b2c00ad60ba1e1a47cbea0153f590b89b698de9b91e240a8427fae4a9d8d48ea10d4fe941ab40f62acca0497e3b9c39967621abb9d6c2863ac1935d4fc193b44e2bb19","clanLevel":25,"progress":1,"nextLevelXp":1991990,"cxpNeeded":0,"nextLevel":25,"membership":0,"invited":null}}}

如果有一种方法我可以轻松地从 angularjs 调用 jquery,或者避免我得到的任何一个错误都会很棒。

【问题讨论】:

    标签: javascript jquery json angularjs jsonp


    【解决方案1】:

    我创建了一个小提琴来找出您的问题可能是什么,并发现您的 return 语句在解析服务中的数据之前被触发了。我已经修改了服务以返回回调,它会正常工作。

    由于我无法在此处模拟您的服务器请求,因此这里是示例 fiddle 和代码 sn-p

    myApp.service('dataService', function($http) {
           console.log("in service!!");
       return {
        getData: function(callback) {
               console.log("http fn");
               resp = "test";
               // from here i get the syntax error
        var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
    
        $http.jsonp(url)
            .success(function(data){
                console.log(data.found);
                resp="success";
                callback(resp);
            });
           }
         }
     });
    

    【讨论】:

    • 它可以在小提琴中使用,但我对callback(resp) 有疑问 .... 对我来说,chrome 说“未定义不是函数”指的是该行
    • 你是否在 getdata 中作为参数传递了回调?
    • 我又看了一遍小提琴,发现我没有传递函数
    • 好的,这就是我要找的。谢谢!
    【解决方案2】:

    看起来有两个原因,anyorigin URL 不起作用。

    1. URL 参数需要正确编码。
    2. 回调应该是JSON_CALLBACK 而不是?

    试试这个...

        var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
        var network = "xbl";
    
        var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
        var wrapURL = "http://anyorigin.com/get?url=" + encodeURIComponent(url) +"&callback=JSON_CALLBACK";
    

    这应该构建这个 URL,它正确地返回一个 JSONP 响应,可以被 angular 使用:

    http://anyorigin.com/get/?url=api.codcp.com%2Fuser_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=JSON_CALLBACK

    看到这个小提琴:Live Demo

    【讨论】:

    • 将http响应返回为return $http.....而不是从响应中返回内容对我来说是个好主意。我使用“成功”和“错误”作为返回响应的原因是为了测试
    【解决方案3】:

    jQuery 的 $.getJSON() 不是 jsonp,所以如果您能够通过 $.getJSON() 检索数据,您也可以使用普通的 $http.get() 来完成(当然可以使用 anyorigin.com)。

    api.codcp.com 似乎不支持 JSONP,无论 URL 中是否存在 callback=?,它都会以普通 JSON 响应。

    【讨论】:

    • 是的,这也是我发现的
    【解决方案4】:

    首先解决这个问题,因为它只是在串联中混合单引号和双引号字符串:

            var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
    

    顺便提一下。 He is 来接你!

    座右铭:

    搜索并销毁

    他全副武装!

    【讨论】:

    • 谢谢,我错过了单引号和双引号的混合,打字太快并尝试不同的东西
    【解决方案5】:

    如果你还没有弄清楚angularjs中的jsonp回调!这对我有帮助:

    $http.jsonp("http://anywebsite.com/?json=get_recent_post&callback=JSON_CALLBACK")
    

    希望对您有所帮助。

    jv

    【讨论】:

      猜你喜欢
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多