为什么我的两个值在第一个 HTTP 请求后未定义?

问题描述 投票:0回答:0

我正在尝试检索城市的输入名称,以显示温度、国家/地区、天气描述和当地时间。

为此,我计划使用第一个 API 来检索预报,第二个 API 使用第一个 API 的经纬度来检索本地时间。

看起来全局变量 latitude 和 longitude 没有及时获取值,因为当我分别 console.log 它们时它们出现,但是当我需要它们用于第二个请求时

const HttpInfoRequest = new XMLHttpRequest();
const HttpTimeRequest = new XMLHttpRequest();

let city, countryCode, temperature, description, latitude, longitude, localTime;

const key = "9b9314b8382b45a5978468be7db26b82";
const url = "https://api.weatherbit.io/v2.0/current?city=";

const timeUrlKey = "RDHZPHTCVSQ2";
const timeUrl = "http://api.timezonedb.com/v2.1/get-time-zone?key=RDHZPHTCVSQ2&format=json&by=position&lat=40.689247&lng=-74.044502";

const countryAbbreviations = "https://github.com/samayo/country-json/blob/master/src/country-by-abbreviation.json";

let submitButton = document.getElementById("submitButton");
submitButton.addEventListener("click", function (event) {
    let inputValue = document.getElementById("city").value;
    HttpInfoRequest.open("GET", url + inputValue + "&key=" + key);
    HttpInfoRequest.send();
    console.log(latitude, longitude);
    HttpTimeRequest.open("GET", timeUrl + "?key=" + timeUrlKey + "&format=json&by=position&lat=" + latitude + "&lng="+ longitude);
    HttpTimeRequest.send();
});

HttpInfoRequest.onreadystatechange = function () {
    if (HttpInfoRequest.readyState == 4 && HttpInfoRequest.status < 300) {
        var responseArray = JSON.parse(HttpInfoRequest.responseText);

        console.log(responseArray);

        city = responseArray.data[0].city_name;
        countryCode = responseArray.data[0].country_code;
        temperature =  responseArray.data[0].temp;
        description = responseArray.data[0].weather.description;
        latitude = responseArray.data[0].lat;
        longitude = responseArray.data[0].lon;
        console.log(latitude, longitude);

        document.getElementById("cityResult").innerHTML = city + ", " + countryCode;
        document.getElementById("temperatureResult").innerHTML = temperature;
        document.getElementById("weatherDescription").innerHTML = description;
    }
};

HttpTimeRequest.onreadystatechange = function () {
    if (HttpTimeRequest.readyState == 4 && HttpTimeRequest.status < 300) {
        var responseArray = JSON.parse(HttpTimeRequest.responseText);

        console.log(responseArray);

    }
};

//TRIVIAL STUFF, IGNORE THIS
$(document).ready(function () {
    $("#darkModeToggle").click(function () {
        $("html").toggleClass("dark");
    });
});

window.onload = function () {
    if (window.jQuery) {
        console.log(
            "jQuery is working,",
            Math.floor(Date.now() / 31536000 / 1000) + " years since 1970"
        );
    } else {
        alert("jQuery fail");
    }
};

我在以下链接中附上了开发者工具控制台结果作为图像:

开发工具控制台

javascript http get xmlhttprequest web-frontend
© www.soinside.com 2019 - 2024. All rights reserved.