我目前正在开发一个显示您所在位置当前天气的网站。我使用的是freecodecamp提供的API https://openweathermap.org/current#geo。我做了一个.ajax()调用但是我的url必须根据用户的url动态。但是,.ajax()调用无法识别变量。我做错了什么?
//jQuery is active
$(document).ready(function(){
//latitude and longitude found
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var userLon=position.coords.longitude;
var userLat=position.coords.latitude;
console.log(userLon);
console.log(userLat);
});
};//navigation bracket
$.ajax({
url:"api.openweathermap.org/data/2.5/weather?lat="+userLat+"&lon="+userLon,
success:function(doc){
//the weather is displayed on html
}
});//ajax call bracket
});//jQuery bracket
答案 0 :(得分:0)
异步请求存在问题。在if condition
$(document).ready(function(){
//latitude and longitude found
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var userLon=position.coords.longitude;
var userLat=position.coords.latitude;
console.log(userLon);
console.log(userLat);
$.ajax({
url:"api.openweathermap.org/data/2.5/weather?lat="+userLat+"&lon="+userLon,
success:function(doc){
//the weather is displayed on html
}
});//ajax call bracket
});
};//navigation bracket
});//jQuery bracket