API函数在加载时返回undefined但在单击

时间:2017-12-14 18:50:27

标签: javascript jquery

我有一个当前与按钮绑定的功能。单击按钮时,我需要的所有数据都可以正常工作。但是,如果我使用Jquery在窗口加载时调用该函数,我收到undefined。从我所做的搜索中我认为它与Async有关,但老实说这完全超出了我的想法。这是我写的:



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;
&#13;
* {
    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;
}
&#13;
<!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>
&#13;
&#13;
&#13;

感谢您提前帮助!

1 个答案:

答案 0 :(得分:0)

你的脚本对我来说很好。我认为发生的事情是你输入了伪造的lat和长变量(需要做一些输入检查),这将为undefined返回response.main,可能为什么你会得到undefined < / p>

我注意到如果有API,API会返回response.error,所以我建议您在继续之前检查它。

我建议添加一些错误处理,如

if(response.error){
  console.error(`OH NO! ${response.error}`);
  return;
}

例如:

var temperature;
var currentTemp;

function GetWeather(latitude, longitude) {
  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);
        if (response.error) {
          console.error(`OH NO! ${response.error}`);
          return;
        }
        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();
};

$(function() {
  navigator.geolocation.getCurrentPosition(function(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    GetWeather(latitude, longitude);
  });
});


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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>