我在线获得了一个示例API。我想将其用于我的Angular示例应用程序。但是,我无法访问下面的静态API。请看看我的代码。
function Hello($scope, $http) {
$http({method: 'GET', url: 'http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'}).
success(function(data) {
alert("Success");
}).
error(function(data){
alert("Error");
});
}
Thank you
Nizam
您需要使用JSONP才能跨域通过Ajax请求数据。好消息是您可以替换以下代码:
function Hello($scope, $http) {
$http.get('http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=atf6ya6bbz3v5u5q8um82pev').
success(function(data) {
alert("success");
$scope.greeting = data["content"];
console.log(data["content"]);
}).
error(function(data){
alert("Error");
});
}
使用以下代码(demo):
function Hello($scope, $http) {
$http
.jsonp('http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=atf6ya6bbz3v5u5q8um82pev&callback=JSON_CALLBACK')
.success(function(data) {
alert("success");
$scope.greeting = data["content"];
console.log(data["content"]);
})
.error(function(data){
alert("Error");
});
}
这是$http.jsonp()
需要的,该方法要求字符串'callback=JSON_CALLBACK'
出现在URL中的某个位置。它将替换为.success()
将引用的生成的函数名称。对于不支持JSONP的服务器,这不能神奇地工作,但在这种情况下,服务器URL可以。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句