現在、ボタンに関連付けられている関数があります。ボタンをクリックすると、必要なすべてのデータが完璧に機能します。しかし、私はJQueryを使用してウィンドウロードでその関数を呼び出すと、私は未定義になります。私が行った検索から、Asyncと何か関係があると思いますが、それは私の頭の中で正直です。ここで私が書いたものです:API関数は、読み込み時にundefinedを返しますが、クリック時に機能します
var latitude;
var longitude;
var temperature;
var currentTemp;
function GetWeather() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", `https://fcc-weather-api.glitch.me/api/current?lat=${latitude}&lon=${longitude}`, true);
xhttp.onload = function (e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
var response = JSON.parse(xhttp.responseText);
temperature = response.main.temp;
document.getElementById("city-text").innerHTML = "City: " + response.name;
document.getElementById("skies-text").innerHTML = "Skies: " + response.weather[0].main + " - " + response.weather[0].description;
document.getElementById("skies-icon").innerHTML = "<img src='" + response.weather[0].icon + "'>";
document.getElementById("temperature-text").innerHTML = "Temperature: " + temperature + "C";
document.getElementById("humidity-text").innerHTML = "Humidity: " + response.main.humidity;
} else {
console.error(xhttp.statusText);
}
}
};
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
};
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
});
$(function() {
GetWeather();
});
function TempConversion() {
return temperature === currentTemp ? currentTemp = temperature * 1.8 + 32 : currentTemp = temperature;
}
currentTemp = temperature;
* {
font-family: roboto;
}
ul {
list-style: none;
padding: 0;
}
.aligner {
display: flex;
align-items: center;
min-height: 95vh;
justify-content: center;
}
.main-container {
background-color: beige;
max-width: 50%;
flex: 1;
text-align: center;
}
.weather-info {
font-size: 1.5em;
font-weight: bold;
}
.weather-info li {
margin: 8px 0px;
}
#skies-icon {
margin: auto;
}
#weather-button {
font-size: 1em;
}
<!DOCTYPE html>
<html>
<head>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="aligner">
<div class="main-container">
<h1>Weather in your area: </h1>
<div class="weather-info">
<ul>
<li id="skies-icon"></li>
<li id="temperature-text"></li>
<li id="city-text"></li>
<li id="skies-text"></li>
<li id="humidity-text"></li>
<li><button id="weather-button" onclick="GetWeather()">GET YOUR WEATHER</button></li>
</ul>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="javascript/script.js"></script>
</body>
</html>
は助けのための高度にありがとうございます!
を? –