Javascript - 尽管使用onreadystatechange,仍会出现null错误

时间:2014-12-16 17:31:02

标签: javascript null openmap

。大家好,我试图将this教程作为一个模块在页面中实现,但我得到一个" weatherData.temperature为null"错误。

我之前得到了一个" weatherData.city为null"错误,但通过在js上使用onreadystatechange修复它。

我在收到错误之前得到了这个,因为我试图将setInnerHTML设置为null,因为我还没有在onreadystatechange中包装脚本,但现在我很难知道为什么我&#39 ; m为不同的代码行收到类似的错误。

如果有人能告诉我我做错了什么,那将非常感激!非常感谢!

(是的,由于我无法控制的原因,我无法将页面上的html和js分开。我知道。我知道......)

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 个答案:

答案 0 :(得分:1)

您可能需要查看readyState中的onreadystatechange

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

        // ...

        getLocationAndWeather();
    }
};

示例:document.readyState


您还需要更改

<a href="temperature" 

<a id="temperature" 

要让switchUnits运行,您需要

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 + ", ";      
};

...所以该功能已发布到window