I am new to writing code and I am trying to create a weather app utilizing JSON & AJAX. I am trying incorporate an if/else statement whereby if user geolocation cannot be obtained(for whatever reason) an alert message pops up notifying the user otherwise coordinates are assigned to variables. At first, I tried doing this:
var endPoint = "geolocation api"//provides user latitude coordinates
$.getJSON(endPoint, function(data){
if(data){
lat = 'lat='+data.loc.split(",")[0]; //assign lat & long coordinates
long = 'lon='+data.loc.split(",")[1];
}else{alert("Weather information cannot be obtained");}
But then I realized that since this is function performs an asynchronous callback the program will assign the variables before data has been received. I then came across these block of codes:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
and this:
$.ajax({
url: '/data/people.json',
dataType: 'json',
success: function(resp) {
data = resp.people;
}
});
The above latter seems like it would work for what I am trying to do but unfortunately I think I am not understanding the logic well so that I can apply it.. Additionally,I then want to make another getJSON call to the openweather api(for weather data) using the coordinates I obtain from the previous. Ultimately, I want the first async call run if coordinates are obtain and if not display an alert message to user
Aucun commentaire:
Enregistrer un commentaire