2017-04-15 18 views
1

我目前正在使用顯示當前天氣的網站。我正在使用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

它是異步請求的問題。在if condition移動ajax呼叫

$(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