2014-07-24 59 views
0

好吧,所以我是AngularJS的新手,並試圖從外部API獲取數據。這樣做的最終結果基本上可以幫助我理解angularjs,使用外部數據,以及爲我的帳戶或我搜索的其他人獲取使命召喚鬼的一些統計數據。AngularJS問題與獲取外部JSON

我知道$ http.jsonp是要走的路,但API並不像CORS那樣真的支持它......我已經說明了這一點。我已經能夠使用jquery進行測試,以確保我可以做到這一點,但無法通過AngularJS瞭解它。我使用whateverorigin和anyorigin從https://stackoverflow.com/a/7910570/1888585https://stackoverflow.com/a/6104416/1888585

一個問題是,我收到HTTP錯誤500(內部服務器錯誤)

沒有他們,我得到關於我得到的JSON的錯誤(這是有效的JSON,使用JSON棉短絨選中) - > '未捕獲的SyntaxError:意外的標記:'

因此,這裏是我:

<!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的輕鬆,或避免任何錯誤我得到的將是巨大的。

回答

2

我創建了一個小提琴來弄清楚你的問題可能是什麼,並發現你的返回語句在解析服務中的數據之前被解僱。我已經修改了該服務,以便返回一個回調,它會正常工作。

既然不能嘲笑你的服務器的請求在這裏是樣品fiddle和代碼段

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); 
     }); 
     } 
    } 
}); 
+0

它的工作原理在小提琴,但我有問題,與'''回調(RESP)'''....我Chrome是說, 「未定義不是函數」引用該行 – Vnge

+0

您是否已經將getdata中的回調函數作爲參數傳遞? – V31

+0

我又看了一下小提琴,意識到我沒有通過功能 – Vnge

1

的jQuery的$.getJSON()不是JSONP,所以如果你能夠通過$.getJSON()檢索數據,你也可以用正常$http.get()一個(當然與使用anyorigin.com的)去做。

看來api.codcp.com不支持JSONP,它使用正常的JSON響應,不管callback=?是否存在於url中。

+0

是啊,這是我發現了什麼,以及 – Vnge

1

修復此對於初學者,因爲它只是在串聯混合單引號和雙引號字符串:

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

順便注意一下。 He is在那裏得到你!

座右銘:

Search & destroy

和他的武裝力量!

+0

謝謝,我錯過了單引號和雙引號混合,打字速度太快,嘗試不同的東西 – Vnge

2

看起來有2個原因導致anyorigin網址無效。

  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響應:

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

看到這個小提琴:Live Demo

+0

對於我來說,返回http響應是個好主意,因爲'''返回$ http .....'''而不是從響應中返回內容。爲什麼我使用「成功」和「錯誤」作爲回報答覆的原因是爲了測試 – Vnge

0

如果你還沒有想出angularjs中的jsonp回調函數!這裏是幫助我的東西:

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

我希望你覺得這有幫助。

合資