我一直在尝试让它工作,从概念上讲,它只需单击标签,它就会调用返回 JSON 结果的 REST 服务,我在其中获取国家/地区名称并将其显示为测试。我正在使用角度。
每次我单击它时,它都会返回状态 0。相信这是PLNKER http://plnkr.co/edit/k3Z6Ufi734oYE4ciVJs8
这是 HTML没什么,只需通过ng单击调用GetInfo函数即可
<!DOCTYPE html>
<html ng-app="mainModule">
<!--http://plnkr.co/edit/k3Z6Ufi734oYE4ciVJs8-->
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link href="style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div><b ng-click="GetInfo()">Click Me</b></div>
<b>{{AdditionalInfo.geobytescountry}}</b>
</body>
</html>
这是角度后端。
var app = angular.module('mainModule', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.name = 'World';
var cityDetailsUrl = "http://gd.geobytes.com/GetCityDetails?callback=?&fqcn=new%20york,%20NY,%20United%20States";
$scope.AdditionalInfo = {};
$scope.GetInfo = function ()
{
$http.get(cityDetailsUrl)
.success(function(data, status, header, config){
console.log('ok');
$scope.AdditionalInfo = data;
console.log(data);})
.error(function(data, status, header, config){
console.log('error');
$scope.AdditionalInfo = data;
console.log(status);});
}
});
提供的链接应该会导致 JSON 响应,因为我在 Web 浏览器中尝试了 id。类似于这个"geobytesinternet":"US","geobytescountry":"United States"
在你的 Plunker 示例中,这似乎是两个问题。
首先,您似乎要使用JSONP
,因此您应该使用$http.jsonp
而不是$http.get
,简单的$http.get
会因为违反同源策略而失败。
另一个问题是您的 URL 应该具有属性 callback=JSON_CALLBACK
而不是 callback=?
JSONP 才能工作。解决这两个问题后,代码似乎可以正常工作。
查看 Plunker: http://plnkr.co/edit/SYB9TI29MOHfNPw1jjQT 的编辑版本
找到了。由于服务器返回的是 jsonp,而不是 json,因此请将您的 url 修改为包含JSON_CALLBACK
: http://gd.geobytes.com/GetCityDetails?callback=JSON_CALLBACK&fqcn=new%20york,%20NY,%20United%20States
并使用$http.jsonp
而不是$http.get
.这是修改后的 Plunker。
http://plnkr.co/edit/Jcs4rQHbINZyLwEN3VeR?p=preview