如何使用JavaScript从URL获取JSON数据。我尝试了以下内容,但没有提供JSON数据。
var GetLocation = function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position, http) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var app_id = '6784429f5eff661309aaa5280a143f97';
var api = "http://api.openweathermap.org/data/2.5";
var weather_api = api +"/weather?appid="+app_id+"&lat="+lat+"&lon="+lon+"&units=metric";
// console.log(weather_api);
var a = http.get(weather_api).then(function(response){
position.jsonList=response.data;
});
console.log(a);
}
打印Weather_api时,它给出了完整的URL,但我陷入了如何从该URL获取JSON数据的情况。
有很少的事情:
- 您必须了解异步呼叫流。
- 如果您正在关注一个教程中的所有内容。
#1
请参阅异步呼叫流。然后了解JavaScript中的承诺。
#2
您遵循的教程是使用angular.js,它具有内置的$http
模块,其中包含get
方法。就您而言,看起来您不使用angular.js&另外,showPosition
函数通过navigator.geolocation.getCurrentPosition
调用,因此调用showPosition
函数时不会通过http
模块。
我使用jQuery
库添加了一个简单的HTTP模块。因此,要使此代码起作用,您必须在HTML文件中包含jQuery
。无论如何,以下代码必须使您了解创建对象&JavaScript&如果您想要其他http请求的其他库,则必须能够替换jQuery。
var http = {
get: function(url) {
return new Promise(function(resolve, reject) {
$.get(url, resolve).fail(reject);
})
}
};
var GetLocation = function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var app_id = '6784429f5eff661309aaa5280a143f97';
var api = "http://api.openweathermap.org/data/2.5";
var weather_api = api +"/weather?appid="+app_id+"&lat="+lat+"&lon="+lon+"&units=metric";
// console.log(weather_api);
var a = http.get(weather_api).then(function(response){
position.jsonList=response;
console.log(position.jsonList);
});
}
注意:请注意,我已经将console.log
移入了承诺处理程序中。