gpt4 book ai didi

javascript - 无法在回调 AngularJS 中访问 JSON 响应

转载 作者:行者123 更新时间:2023-11-30 17:52:03 25 4
gpt4 key购买 nike

在我的网络选项卡中,我看到返回的响应,但由于某种原因我无法访问数据。

这是直接链接: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);
});

$资源

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 指定的回调函数需要驻留在全局范围内,然后您需要“重新 Angular 化”响应数据。

这是一个使用 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);
});
}

关于javascript - 无法在回调 AngularJS 中访问 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18807901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com