$ http.get和$ http.JSONP未能获得谷歌api响应
我试图通过使用angularjs $ http .get方法和$ http.JSONP方法获得“http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true®ion=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®ion=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);
});
}
}]);
在浏览器中运行此代码时,它不返回任何内容。引发错误。 你能帮我解决这个问题吗?
与角JSONP工作,你需要... ?callback=JSON_CALLBACK
传递给get调用..
例如
$http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true®ion=USA&callback=JSON_CALLBACK"}).
阅读更多关于它here
感谢您的答案。我尝试过?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
你有没有通过提供的链接?你有没有试过看更多... – harishr 2015-03-13 06:53:13
您的代码具有唯一的问题是,有参数isno例如HTTP方法JSONP。在你的情况下,你需要GET。所以用这个来代替:
$scope.method = 'GET';
感谢您的回答。我试过$ scope.method ='GET'; 由于Request失败,这也不能正常显示错误。此网址http://plnkr.co/edit/I6qAMbsvLwM3vgZFQa0S?p=preview也显示相同的错误“请求失败” – 2015-03-13 06:26:45
我可以看到,我提供的演示完美的作品,不知道什么对你来说失败。 – dfsq 2015-03-13 06:47:19
你必须从JSONP到GET改变你的请求方法。
$scope.getlocation=function(){
$scope.method = 'get';
$http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true®ion=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”}测试它
希望你得到你正在寻找的东西。
提及您遇到的错误 – 2015-03-13 06:06:05
状态码:404请求失败响应...您能否告诉我如何调用此api“http://maps.google.com/maps/api/geocode/json?address =加拿大和传感器=真正的地区=美国“通过angularjs – 2015-03-13 07:22:57