javascript - AngularJS Service for XHR -
i trying create service in angularjs fetch me json data website. wrapped service in factory method shown below
app.factory('httpservice', function($http) { delete $http.defaults.headers.common['x-requested-with']; return { getdata : function() { var url = "http://www.reddit.com/.json?callback=json_callback"; return $http.jsonp(url).then( function(result) { return result; }); } } });
the problem i'm coming across receive error uncaught syntaxerror: unexpected token :
. when use get()
instead of json()
501
/cors error.
the urls trying fetch data are: http://api.4chan.org/b/1.json http://www.reddit.com/.json
following link jsfiddle rest of code.
http://jsfiddle.net/fatgamer85/adpue/3/
does 1 has idea on how solve this?
edit: have managed data , solved issue. sza
following code i've used if anyone's interested
var myapp = angular.module("client", []); myapp.factory('myxhrservice', function($http) { delete $http.defaults.headers.common['x-requested-with']; return { getdata : function(url) { return $http.jsonp(url).then( function(result) { return result.data; } ); } } }); myapp.controller('mainctrl', function($scope, myxhrservice) { $scope.xhrdata = {}; $scope.data = {}; $scope.url = "http://www.reddit.com/.json?jsonp=json_callback"; myxhrservice.getdata($scope.url).then(function(data) { var xhrdata = angular.fromjson(data); $scope.xhrdata = xhrdata.data.children; }); }); myapp.config(function($httpprovider){ $httpprovider.defaults.usexdomain = true; delete $httpprovider.defaults.headers.common['x-requested-with']; });
the main difference here callback in url parameters jsonp
apart that, works fine , dandy.
i think may relate api endpoint issue of reddit.com. if try api, work using jsonp
var url = "http://www.reddit.com/top.json?jsonp=json_callback";
for api /.json
, suggest implement server side code retrieve data though returns valid json somehow can't accessed correctly across domain.
Comments
Post a Comment