在我的网络选项卡中,我看到返回的响应,但由于某种原因我无法访问数据。
这是直接链接:https://github.com/users/gigablox/contributions_calendar_data
使用 Angular 1.2 rc2。尝试了几种不同的方法...
$http
var url = "https://github.com/users/gigablox/contributions_calendar_data?callback=JSON_CALLBACK";
$http.jsonp(url).success(function(data){
console.log(data);
});
$resource
var handle = $resource('https://github.com/users/gigablox/contributions_calendar_data',{},{
get:{
method:'JSONP',
isArray: false, //response is wrapped as an array. tried true and false
params:{callback:'JSON_CALLBACK'}
}
});
handle.get().$promise.then(
function(data){
console.log(data);
}).
function(error){
console.log(error); //undefined but 200 OK on response?
});
这里的问题是您正在请求一个平面文件,因此服务器没有将数据包装在由 jsonp_callback
querystring 参数指定的 javascript 函数调用中。 进一步的 CORS 阻止您直接使用 $http/xhr 获取文件。
通常,如果使用 $http.jsonp,则指定的回调函数需要驻留在全局范围内,然后需要"重新定义"响应数据。
下面是一个使用 wordpress API 的示例: http://jsfiddle.net/Rjfre/23/
.HTML
<div ng-controller="MyCtrl" id='ctl'>
<h2 ng-show="data">Data from callback</h2>
<pre>{{data}}</pre>
<h2 ng-show="success">Success</h2>
<pre>{{success}}</pre>
<h2 ng-hide="data">Error</h2>
<pre>{{error}}</pre>
</div>
脚本
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $http) {
$scope.name = 'Superhero';
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";
$http.jsonp(url).then(
function(s) { $scope.success = JSON.stringify(s); },
function(e) { $scope.error = JSON.stringify(e); } );
}
function jsonp_callback(data) {
var el = document.getElementById('ctl');
var scope = angular.element(el).scope();
scope.$apply(function() {
scope.data = JSON.stringify(data);
});
}