Javascript - Getting null error despite using onreadystatechange

∥☆過路亽.° 提交于 2019-12-02 20:32:01

问题


. Hello y'all, I'm trying to implement this tutorial as a module in a page but I am getting a "weatherData.temperature is null" error.

I had previously been getting a "weatherData.city is null" error but fixed it by using onreadystatechange on the js.

I get that before I was getting the error because I was trying to setInnerHTML to something that was null because I hadn't wrapped the script in the onreadystatechange but now I'm stumped as to why I'm getting a similar error for a different line of code.

If anyone could tell me what I'm doing wrong it would be very much appreciate! Thank you so much!

(And yes, for reasons beyond my control I cannot separate the html and js on the page. I know. I know...)

HTML:

<div id="weather-web-app">
    <section>
        <h1 id="city">Weather Web App</h1>
        <p>
            <a href="temperature" href="#" onclick="switchUnits(); return false;" title="Click to switch between metric and imperial units">
            </a>
            <span id="weather">
                Current temperature and weather conditions
            </span>
        </p>
    </section>

</div>

JS

<script>
document.onreadystatechange = function(){
    var weatherData = {
        city:               document.querySelector("#city"),
        weather:            document.querySelector("#weather"),
        temperature:        document.querySelector("#temperature"),
        temperatureValue:   0,
        units:              "°C"
    };

    function switchUnits(){
        if (weatherData.units == "°C"){
            weatherData.temperatureValue = weatherData.temperatureValue * 9/5 + 32;
            weatherData.units = "°F";
        } else {
            weatherData.temperatureValue = (weatherData.temperatureValue - 32) * 5/9;
            weatherData.units = "°C";
        }

        weatherData.temperature.innerHTML = weatherData.temperatureValue + weatherData.units + ", ";      
    }

    function getLocationAndWeather(){
        if (window.XMLHttpRequest){
            var xhr = new XMLHttpRequest();
            xhr.addEventListener("load", function() {
                var response = JSON.parse(xhr.responseText);

                console.log(response);
                var position = {
                    latitude:   response.latitude,
                    longitude:  response.longitude
                };
                var cityName = response.city;

                var weatherSimpleDescription    = response.weather.simple;
                var weatherDescription          = response.weather.description;
                var weatherTemperature          = response.weather.temperature;

                weatherData.temperatureValue = weatherTemperature;

                loadBackground(position.latitude, position.longitude, weatherSimpleDescription);

                weatherData.city.innerHTML          = cityName;
                weatherData.weather.innerHTML       = ", " + weatherDescription;
                weatherData.temperature.innerHTML   = weatherTemperature + weatherData.units;
            }, false);

            xhr.addEventListener("error", function(err){
                alert("Could not complete the request");
            }, false);

            xhr.open("GET", "https://fourtonfish.com/tutorials/weather-web-app/getlocationandweather.php?owapikey=YOUROPENWEATHERMAPKEY&units=metric", true);
            xhr.send();
        } else {
            alert("Unable to fetch location and weather data.");
        }           
    }

    function loadBackground(lat, lon, weatherTag) {
        var script_element = document.createElement('script');

        script_element.src = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=YOURFLICKRAPIKEY&lat=" + lat + "&lon=" + lon + "&accuracy=1&tags=" + weatherTag + "&sort=relevance&extras=url_l&format=json";

        document.getElementsByTagName('head')[0].appendChild(script_element);
    }

    function jsonFlickrApi(data){
        if (data.photos.pages > 0){
            var photo = data.photos.photo[0];
            document.querySelector("body").style.backgroundImage = "url('" + photo.url_l + "')";
            document.querySelector("#image-source").setAttribute("href", "http://www.flickr.com/photos/" + photo.owner + "/" + photo.id);
        } else {
            document.querySelector("body").style.backgroundImage = "url('https://fourtonfish.com/tutorials/weather-web-app/images/default.jpg')";
            document.querySelector("#image-source").setAttribute("href", "https://www.flickr.com/photos/superfamous/310185523/sizes/o/");
        }
    }

    getLocationAndWeather();
}
</script>

回答1:


You likely need to check the readyState in your onreadystatechange.

document.onreadystatechange = function () {
    if (document.readyState === "interactive") {

        // ...

        getLocationAndWeather();
    }
};

Sample: document.readyState


Also you need to change

<a href="temperature" 

to

<a id="temperature" 

To get switchUnits running, you'll need

switchUnits = function switchUnits () {
    if (weatherData.units == "°C"){
        weatherData.temperatureValue = weatherData.temperatureValue * 9/5 + 32;
        weatherData.units = "°F";
    } else {
        weatherData.temperatureValue = (weatherData.temperatureValue - 32) * 5/9;
        weatherData.units = "°C";
    }

    weatherData.temperature.innerHTML = weatherData.temperatureValue + weatherData.units + ", ";      
};

... so the function is published to the window.



来源:https://stackoverflow.com/questions/27510496/javascript-getting-null-error-despite-using-onreadystatechange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!