2016-12-28 98 views
1

我正試圖創建一個天氣應用程序,向OpenWeatherMap發送Ajax請求。我在w.getWeatherFunc中有一個錯誤,當我給函數sendRequest的w.weather的參數,然後給函數displayFunc,我接下來調用相同的參數。如何保存函數調用之間的參數值?

以下是我在控制檯已經有了:

遺漏的類型錯誤:在displayFunc的不確定 無法讀取屬性 '天氣'(weather.js:46) 在weather.js:78

我該如何解決這個問題並使其工作?

function Weather() { 
    var w = this; 

    var weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?'; 
    var appid = '&appid=c0a7816b2acba9dbfb70977a1e537369'; 
    var googleUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='; 
    var googleKey = '&key=AIzaSyBHBjF5lDpw2tSXVJ6A1ra-RKT90ek5bvQ'; 

    w.demo = document.getElementById('demo'); 
    w.place = document.getElementById('place'); 
    w.description = document.getElementById('description'); 
    w.temp = document.getElementById('temp'); 
    w.humidity = document.getElementById('humidity'); 
    w.getWeather = document.getElementById('getWeather'); 
    w.addCityBtn = document.getElementById('addCity'); 
    w.rmCityBtn = document.getElementById('rmCity'); 
    w.icon = document.getElementById('icon'); 
    w.wind = document.getElementById('wind'); 
    w.time = document.getElementById('time'); 
    w.lat = null; 
    w.lon = null; 
    w.cityArray = []; 
    w.weather = null; 

    function sendRequest (url, data) { 

     var request = new XMLHttpRequest(); 
     request.open('GET', url, true); 
     request.send(); 

     request.onreadystatechange = function() { 
      if (request.readyState == 4 && request.status == 200) { 
        data = JSON.parse(request.responseText); 
        console.log(data); 
        return data; 
      } else { 
       console.log(request.status + ': ' + request.statusText); 
      } 
     } 

    } 

    function displayFunc (obj) { 

     console.log('obj ' + obj); 
     w.icon.src = 'http://openweathermap.org/img/w/' + obj.weather[0].icon + '.png'; 

     var timeNow = new Date(); 
     var hours = timeNow.getHours(); 
     var minutes = timeNow.getMinutes() < 10 ? '0' + timeNow.getMinutes() : timeNow.getMinutes(); 
     w.time.innerHTML = hours + ':' + minutes; 

     w.place.innerHTML = 'Place: ' + obj.name; 
     w.description.innerHTML = "Weather: " + obj.weather[0].description; 
     w.temp.innerHTML = "Temperature: " + w.convertToCels(obj.main.temp) + "°C"; 
     w.humidity.innerHTML = "Humidity: " + obj.main.humidity + '%'; 
     w.wind.innerHTML = 'Wind: ' + obj.wind.speed + ' meter/sec'; 
    } 


    w.convertToCels = function(temp) { 
     var tempC = Math.round(temp - 273.15); 
     return tempC; 
    } 


    w.getWeatherFunc = function() { 

     if (navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(function(location){ 
       w.lat = location.coords.latitude; 
       w.lon = location.coords.longitude; 

       var url = weatherUrl + 'lat=' + w.lat + '&lon=' + w.lon + appid; 

       var result = sendRequest(url, w.weather); 
       console.log(result);  
       displayFunc(result); 
      }); 
     } else { 
      alert('Browser could not find your current location'); 
     } 
    } 


    w.addCityBtn.onclick = function() { 
     var newCity = prompt('Please insert city', 'Kiev'); 

     var gUrl = googleUrl + newCity + googleKey; 
     var newCityWeather = null; 
     sendRequest(url, newCityWeather); 

     var location = newCityWeather.results[0].geometry.location; 
     var newUrl = weatherUrl + 'lat=' + location.lat + '&lon=' + location.lng + appid; 

     sendRequest(newUrl, w.weather); 

      displayFunc(newCity); 
      w.cityArray.push(newCity); 
     } 

    window.onload = w.getWeatherFunc; 

    setInterval(function() { 
     w.getWeatherFunc(); 
    }, 900000); 

} 

回答

0

您的ajax 返回返回瀏覽器引擎。由於它的異步您需要創建一個回調:

function sendRequest(url,data,callback){ 

//if the data was received 
callback(data); 
} 

使用這樣

sendRequest("yoururl",data,function(data){ 
displayFunc(data); 
}); 
+0

是的,這工作!非常感謝! – Olga

0

當您第一次將obj傳遞給函數時,它會將其保存在一個更高的範圍內。在那之後,如果你不傳遞對象,你之前保存的對象將被使用。

var objBkp; 
function displayFunc (obj) { 
    if(undefined === obj) obj = objBkp; 
    else objBkp = obj; 
    // rest of code here 
} 
+0

還是得到了同樣的錯誤 – Olga

+0

我不是試圖解決任何錯誤,我是在回答你問的問題。佩爾帕斯,你應該考慮重申這個問題。 –

+0

我相信這就是我在這裏所做的:我有一個全局變量w.weather,我將它傳遞給函數,並且它應該會改變它的值,但它不是 – Olga

0

在你sendRequest你逝去的w.weather的唯一的價值,而不是它的參考。 JavaScript不會通過值或引用傳遞變量,而是通過sharing。所以,如果你想給的價值,您的變量,你應該這樣做,你的函數裏面sendRequest

request.onreadystatechange = function() { 
    if (request.readyState == 4 && request.status == 200) { 
     w.weather = JSON.parse(request.responseText); 
     console.log(data); 
     return data; 
    } else { 
     console.log(request.status + ': ' + request.statusText); 
    } 
} 

另外,如果您正在使用的屬性,你沒有通過他們在功能作爲參數。除此之外,如果您還創建了get()set()

+0

您一般正確,但鏈接沒有任何待辦事項你的答案。空是原始類型,因此按值傳遞。 –

0

getWeatherFunc中的console.log(result);會給您帶來什麼? 我看到的問題是,在displayFunc傳遞的參數是未定義的。

+0

是的,它給出了undefined – Olga

+0

我知道你還沒有評論,但這是一個評論。請刪除它 –

相關問題