2

我正在尝试构建一个示例应用程序,该应用程序将使用 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'];
4

1 回答 1

2

在我看来,问题出在您的资源上。当我检查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 响应。使用请求参数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 应用程序中防止它们的信息。

于 2013-04-16T18:37:01.473 回答