2014-09-12 73 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])」