2014-09-12 52 views
1

我需要对外部API执行Ajax调用来获取JSON格式的数据,但我没有得到任何结果。Ajax调用外部API来获取JSON - 使用JSONP

我有这样的控制器:

angular.module('myApp').controller('myCtrl', function($scope, MyService) { 

     $scope.list = MyService.fetchAll(); 
}); 

而这种服务,使Ajax请求到另一个域:

var MyService = function($http) { 
    this.fetchAll = function() { 
     console.log('here1'); 

     $http.jsonp('http://other.domain.com/list/?allback=JSON_CALLBACK').success(function(data) 
      console.log('here2'); 
      return angular.fromJson(data); 
     }).error(function(data, status, headers, config) { 
      console.log('here3'); 
      console.log(status); 
     }); 
    }; 
}; 

angular.module('myApp').service('MyService', MyService); 

的json返回的就是:

[1,2 ,3,4,5]

当执行代码/请求我没有得到例外的结果,代码中。 success()永远不会被执行。我得到控制台:

here1 
here3 
404 

任何有关如何实施此最佳方法的建议将不胜感激。我是新手。

+1

你确定json会回来吗?你的函数似乎在抛出一个404错误,这意味着它根本没有触及api – theDarse 2014-09-12 19:24:21

+0

是的,请求已经完成,我得到结果[1,2,3,4,5] ...(在网络部分检查,在DevTools) – leticia 2014-09-12 19:40:22

回答

1

你的console.log(状态)打印404,这意味着:

The 404 or Not Found error message is a HTTP standard response code indicating that the client was able to communicate with a given server, but the server could not find what was requested.

仔细检查URL地址。

您可以使用工厂使AJAX调用方式: (这里http://jsfiddle.net/ty69u6tL/4/样品)

厂:

app.factory('MyService', function ($http, $q) { 

    ///////////////////////////////////////////////////////////// 
    // put your url here://////////////////////////////////////// 
    ///////////////////////////////////////////////////////////// 
    var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK"; 


    this.fetchAll = function() { 
     var deferred = $q.defer(); 
     console.log('here1'); 
     $http.jsonp(url).success(function (data) { 
      console.log('here2'); 
      deferred.resolve(angular.fromJson(data)); 
     }).error(function (data, status, headers, config) { 
      console.log('here3'); 
      console.log(status); 
      deferred.reject(data, status, headers, config); 
     }); 
     return deferred.promise; 
    }; 
    return this; 
}); 

控制器:

app.controller('jsonp_example', function ($scope, MyService) { 
    $scope.data = {}; 

    $scope.doRequest = function() { 
     MyService.fetchAll().then(onSucess, onError); 

     function onSucess(response) { 
      $scope.data = response; 
     } 

     function onError() { 
      alert("Cant get data "); 
     }   
    }; 
}); 

HTML *

<div ng-app="app"> 
    <div ng-controller="jsonp_example"> 
     <button ng-click="doRequest()">Make JSONP request</button> <pre> {{data | json}}</pre> 

    </div> 
</div> 
+0

谢谢,我再次做了......但我甚至得到了请求响应代码200(和json)在DevTools网络部分,我知道是奇怪的,我得到404和200在其他方面 – leticia 2014-09-12 22:21:01

+1

请参阅工作示例http://jsfiddle.net/ty69u6tL/3/只需更新您的网址 – sylwester 2014-09-12 22:47:25

+0

请在您的答案中设置代码(是重新主人在这里为他人)接受它。主要问题是请求的API不返回回调引用,只返回JSON [1,2,3,4,5]。取而代之的是需要返回像“JSON_CALLBACK([1,2,3,4,5])”随着你的代码和API的变化,所有工作正常 – leticia 2014-09-13 06:11:34

1

请记住,外部json请求是一个异步操作,并且这是问题的根源,当您调用'fetchAll()'时,它不会等待请求完成并返回值。为了纠正这种情况,您必须从您的服务中退还承诺,并将数据分配给它的'即时'功能。

var MyService = function($http, $q) { 
    this.fetchAll = function() { 
     var deferred = $q.defer(); 


     $http.jsonp('http://other.domain.com/list/?allback=JSON_CALLBACK').success(function(data){ 
      console.log('here2'); 
      deferred.resolve(angular.fromJson(data)); 
     }).error(function(data, status, headers, config) { 
      console.log('here3'); 
      deferred.reject(status); 
     }); 

     return deferred.promise; 
    }; 
return this; 
}; 

而在你的控制,这样做:

angular.module('myApp').controller('myCtrl', function($scope, MyService) { 
    MyService.fetchAll.then(function(data){ 
     $scope.list = data; 
    }) 
}, function(error){ 
    console.log(error); 
    // Decide what to do with your $scope.list in case of an error 
    $scope.list = null; 
}); 
+0

谢谢.. + 1我更新了代码,但现在变得“TypeError:undefined是不是一个函数”在这个控制器行“MyService.fetchAll.then(” – leticia 2014-09-12 19:52:49

+0

我想说函数fetchAll应该返回延期.promise而不是$ q.promise – user3281440 2014-09-12 20:35:25

+0

@ user3281440你是绝对正确的,那是我的错误,谢谢你指出了。 – Fedaykin 2014-09-13 11:41:44

1

对于档案的目的,我终于做到了如下(我个人认为是最简单的方法):我有这个

在我的服务:

this.fetchAll = function() { 

     return $http.jsonp("<here API Endpoint>").then(function(response){ 
       return response.data; 
     }); 
}; 

在我的控制器:

MyService.fetchAll().then(function(data) { 
    requestResult = data; 
}); 

只是注意:主要概率lem是请求的API不返回回调引用,只返回JSON [1,2,3,4,5]。相反,需要返回像“JSON_CALLBACK([1,2,3,4,5])”