我正在尝试构建一个示例应用程序,该应用程序将使用 JSONP 获取数据来填充。我把它贴在 http://angular.onagrag.com/然后单击“注册”。
我尝试加载的文件位于 http://api.onagrag.com/data.json
当我访问http://angular.onagrag.com/register时它触发对象的错误方法(并且触发两次)
这是我正在使用的 Angular js 文件(它也位于 http://angular.onagrag.com/js/test.js
如果我使用本地数据(例如使用 $http.get 方法而不是 $http.jsonp 方法),它运行良好,但不适用于 jsonp。如有任何帮助,我们将不胜感激!
var App = angular.module('popdust', ['ngResource']).config(['$locationProvider', function($location) {
$location.html5Mode(true).hashPrefix('!')
}]);
App.config(['$routeProvider', function($routes) {
$routes.when('/register',{
templateUrl : '/templates/register.html',
controller : RegisterCtrl
});
$routes.when('/',{
templateUrl : '/templates/home.html',
controller : HomeCtrl
});
}]);
var HomeCtrl = function($scope, $http, $location) {
$scope.title = 'We are home';
$scope.obj = ['one', 'two','three'];
};
var RegisterCtrl = function($scope, $http, $location) {
$scope.title = 'Register!';
$scope.handleData = function(data){
$scope.fields = data;
}
$scope.fetchjsonp = function(){
$http.jsonp('http://api.onagrag.com/data.json?callback=JSON_CALLBACK').success(function(data){
alert("success");
}).error(function(data, status, headers, config) {
alert("YOU FAIL");
});
}
$scope.fetch = function(){
$http.get('js/data.json').success($scope.handleData);
}
$scope.fetchjsonp();
};
HomeCtrl.$inject = ['$scope','$http','$location'];
RegisterCtrl.$inject = ['$scope','$http','$location'];
最佳答案
在我看来问题出在你的资源上。当我检查http://api.onagrag.com/data.json?callback=JSON_CALLBACK时我收到以下回复:
[{
"id" : "first_name",
"title" : "First Name",
"description" : "The name your parents gave you"
},{
"id" : "last_name",
"title" : "Last Name",
"description" : "In Spanish, it's called your apellido (or something like that)"
}]
这不是有效的 JSONP response 。使用请求参数callback=nameOfCallbackFn
,响应应该是对名为nameOfCallbackFn 的函数的单个函数调用(结果作为唯一参数)。
更新:提供 JSONP 服务的服务器必须读取 callback
请求参数,并使用对请求方法名称进行方法调用的文件进行响应。当你使用 Angular $http.jsonp
方法时,Angular 会将回调请求参数更改为正确的 Angular jsonp 回调方法名称(atm 它们似乎被命名为 angular.callback._0
、..._1
等)。您无法提供静态文件,因为该名称可能会根据一个请求更改为另一个请求。这在我原来的回答中并不清楚。
类似这样的事情:
nameOfCallbackFn ( [{
"id" : "first_name",
"title" : "First Name",
"description" : "The name your parents gave you"
},{
"id" : "last_name",
"title" : "Last Name",
"description" : "In Spanish, it's called your apellido (or something like that)"
}] );
其中nameOfCallbackFn
由 Angular 指定。
JSONP 有一些潜在的安全漏洞 - 您可以阅读有关它们的更多信息以及如何在您的 Angular 应用程序中防止它们 here .
关于angularjs + jsonp 返回失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16044029/