簡體   English   中英

json Flickr Api使用Java腳本未定義

[英]json Flickr Api undefined using Javascript

您好,我正在嘗試完成本教程,但他們在說明中遺漏了一些關鍵部分。 我已經找出了一些缺失的東西,但是我無法插入由Photo Search API返回的flickr圖像作為背景。 我不斷收到ReferenceError: jsonFlickrApi is not defined盡管我可以看到所需的數據,但ReferenceError: jsonFlickrApi is not defined為控制台錯誤。 如果有人能解釋我在做什么錯,我將不勝感激,謝謝!

JS:

document.onreadystatechange = function(){
    if(document.readyState === "interactive"){
        var weatherData = {
            city:               document.querySelector("#city"),
            weather:            document.querySelector("#weather"),
            temperature:        document.querySelector("#temperature"),
            temperatureValue:   0,
            units:              "°F"
        };

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

                    console.log(response);
                    var position = {
                        latitude:   response.latitude,
                        longitude:  response.longitude
                    };
                    var cityName = response.city;
                    if(cityName =="Earth"){
                        /*IP-based location detection failed.*/
                        /*Ask user where he or she lives*/
                        getWeatherForLocation();
                    } else {
                    var weatherSimpleDescription    = response.weather.simple;
                    var weatherDescription          = response.weather.description;
                    var weatherTemperature          = Math.round(response.weather.temperature * 9/5 + 32);

                    weatherData.temperatureValue = weatherTemperature;

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

                    weatherData.city.innerHTML          = cityName;
                    weatherData.weather.innerHTML       = ", " + weatherDescription;
                    weatherData.temperature.innerHTML   = weatherTemperature + weatherData.units;
                    console.log("Finished proessing and displaying weather info...");

                    }
                }, 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=ab2497c49afeabeff924fb4bd2288ee5&units=metric", true);
                xhr.send();
                console.log("Requesting weather info...");
            } else { 
                alert("Unable to fetch location and weather data.");
            }
        }

        function getWeatherForLocation(){
            var location = prompt("Your location could not be detected automatically, can you tell me where you live?");
            if (location != null){
                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/");

                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 lat = response.latitude;
                    var lon = response.longitude;
                    var cityName = response.city;

                    var weatherSimpleDescription = response.weather.simple;
                    var weatherDescription = response.weather.description;
                    var weatherTemperature = Math.round(response.weather.temperature);
                    weatherData.temperatureValue = weatherTemperature;

                    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/getweatherforlocation.php?owapikey=45713cc0d54c4bfa1c7efbbdbd1c6c2b&units=metric&location=" + location, true);
                xhr.send();
            }
            else{
                alert("Unable to fetch the 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=0677de6a559772c8cb27dd22219dfa0c&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];
                    console.log("Photo data: " + photo);
                    document.querySelector("weather-web-app").style.backgroundImage = "url('" + photo.url_l + "')";
                    document.querySelector("#image-source").setAttribute("href", "http://www.flickr.com/photos/" + photo.owner + "/" + photo.id);
                }
                else{
                    document.querySelector("weather-web-app").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_element.src = "...&accuracy=1" +  + &sort=relevance...";

第二,如我所見,使用JSONP的Flickr api需要在接收方定義回調函數。 由於您已將此函數放入偵聽器並置於條件中,因此它將是不確定的。

放在外面:

document.onreadystatechange = function() {
    ...
}
function jsonFlickrApi() {...}

知道了

Flikr不喜歡

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

具體來說,它不喜歡我的weatherTag變量。

所以

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

相反工作正常。

謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM