2015-03-13 42 views
0

我試圖通過使用angularjs $ http .get方法和$ http.JSONP方法獲得「http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true&region=USA」的api響應。但它不能正常工作,它什麼都不返回。當我通過REST客戶端和瀏覽器嘗試這個API,它提供了JSON數據,狀態碼200

這裏是我的代碼... 的index.html

<html ng-app="myApp"> 
<body ng-controller="MyCtrl"> 
<button ng-click="getlocation()">Get Location</button> 
</body> 
</html> 

app.js

var app = angular.module('myApp',[]); 

app.controller('MyCtrl', ['$scope','$http',function ($scope,$http) { 


    $scope.getlocation=function(){ 

     $scope.method = 'JSONP'; 
     $http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true&region=USA"}). 
     success(function(data, status) { 

      $scope.status = status; 
      $scope.data = data; 
      alert(JSON.stringify(data)); 
     }). 
     error(function(data, status) { 
      $scope.data = data || "Request failed"; 
      $scope.status = status; 
      alert($scope.data+$scope.status); 
     }); 

    } 
}]); 

在瀏覽器中運行此代碼時,它不返回任何內容。引發錯誤。 你能幫我解決這個問題嗎?

+0

提及您遇到的錯誤 – 2015-03-13 06:06:05

+0

狀態碼:404請求失敗響應...您能否告訴我如何調用此api「http://maps.google.com/maps/api/geocode/json?address =加拿大和傳感器=真正的地區=美國「通過angularjs – 2015-03-13 07:22:57

回答

1

與角JSONP工作,你需要... ?callback=JSON_CALLBACK傳遞給get調用..

例如

$http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true&region=USA&callback=JSON_CALLBACK"}). 

閱讀更多關於它here

+0

感謝您的答案。我嘗試過?callback = JSON_CALLBACK。但它不工作...試試這個$ http({方法:$ scope.method,url:「http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true®ion=USA&callback=JSON_CALLBACK 「})在plunker演示:http://plnkr.co/edit/spDiD4V6JCCXrtRNDV11?p =預覽...一旦你完成了這個你可以理解我的問題 – 2015-03-13 06:29:51

+0

你有沒有通過提供的鏈接?你有沒有試過看更多... – harishr 2015-03-13 06:53:13

0

您的代碼具有唯一的問題是,有參數isno例如HTTP方法JSONP。在你的情況下,你需要GET。所以用這個來代替:

$scope.method = 'GET'; 

演示:http://plnkr.co/edit/I6qAMbsvLwM3vgZFQa0S?p=preview

+0

感謝您的回答。我試過$ scope.method ='GET'; 由於Request失敗,這也不能正常顯示錯誤。此網址http://plnkr.co/edit/I6qAMbsvLwM3vgZFQa0S?p=preview也顯示相同的錯誤「請求失敗」 – 2015-03-13 06:26:45

+0

我可以看到,我提供的演示完美的作品,不知道什麼對你來說失敗。 – dfsq 2015-03-13 06:47:19

0

你必須從JSONPGET改變你的請求方法。

$scope.getlocation=function(){ 

     $scope.method = 'get'; 
     $http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true&region=USA"}). 
     success(function(data, status) { 

      $scope.status = status; 
      $scope.data = data; 
      alert(JSON.stringify(data)); 
     }). 
     error(function(data, status) { 
      $scope.data = data || "Request failed"; 
      $scope.status = status; 
      alert($scope.data+$scope.status); 
     }); 

    } 

我已經從我的身邊和回報

對象{結果:數組[1],狀態: 「OK」}測試它

希望你得到你正在尋找的東西。