无法访问回调 AngularJS 中的 JSON 响应
cant access JSON response in callback AngularJS
在我的网络选项卡中,我看到返回的响应,但由于某种原因我无法访问数据。
这是直接链接: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);
});
}
相关文章:
- 单击按钮更改加载到表中的JSON文件
- 将字符串转换为GWT中的JSON对象(JSNI)
- 使用jquery解析phonegap中的json数据
- 将javascript中的JSON输出为不带jquery的列表
- 如何使用NodeJS修改文件中的JSON值
- 对数组中的json对象进行迭代
- 使用 js 删除本地存储中的 json 对象
- 如何用HTML中的JSON外部文件填充下拉按钮
- 使用$http的angular js中的JSON数据-data.push()
- AJAX请求中的JSON对象为Null或空
- 隐藏HTML元素中的JSON编码和解码
- 分析sharepoint 2010 Web部件中的json
- 将MySQL中的JSON导入Google图表
- 从表中的 JSON 数组获取数据
- 如何更新文件中的 JSON 数据
- 使用 Bean 对象中的 JSON 构造数组
- JavaScript 中的 JSON 解析
- 节点.js中的 JSON 数组
- JavaScript 中的 JSON.stringify () 错误
- 使用 PHP 中的 JSON 进行 JSON 解析