2016-12-06 71 views
1

这是我的网页看起来像:http://prntscr.com/dg6dmm和我codepen链接:http://codepen.io/johnthorlby/pen/dOmaEropenweathermap weather.icon是显示为未定义

我想了解从API调用weather.icon和使用图标标识(在此示例中为“02n”),并根据天气情况显示https://openweathermap.org/weather-conditions的图标,但这只是显示为未定义的,但如果您在整个调用中查看屏幕截图,则图标为“02n”。

这里是我的html:

<div class="main" id="temp"> 
    <h1>Weather!</h1> 
    <h2></h2> 
    <h3></h3> 
    <p></p> 
    <img src=""> 
</div> 

这里是我的CSS:

html, body { 
    margin: 0; 
    padding: 0; 
    font-family: 'Dosis', sans-serif; 
    background-color: #BEBDCE; 
} 
.main{ 
    text-align: center; 
    background-color: #8E9EBC; 
    padding: 10px; 
} 
.main h1 { 
    margin: 0; 
} 

这里是我的JS:

$(document).ready(function() { 
    var api = "43881a1bf31fb1b7225348b3f7839a9d"; 
    var city = "Oslo"; 
    var wData; 
    $.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=" + api, function(json) { 
    wData = JSON.stringify(json); 
    var name = JSON.stringify(json.name + ", " + json.sys.country); 
    var temp = JSON.stringify(json.main.temp); 
    var icon = JSON.stringify(json.weather.icon); 
    temp = Math.round(temp); 
    //update h2 with city, country and temperature and testing to see what weather.icon is but comes back as undefined 
    $("#temp h2").text("The temperature in " + name + " is " + temp + "°C " + icon); 
    //testing to see if there is a icon in the api call which there is "02n" 
    $("#temp p").text(wData); 
    //display image of weather type from https://openweathermap.org/weather-conditions 
    $("#temp img").attr("src", "http://openweathermap.org/img/w/" + icon + ".png"); 
    }); 
}); 

回答

0

天气是在JSON数组,你需要将数据从其中正确拉出。此外,你的输出字符串有“”,所以我们需要删除它们。

var icon = JSON.stringify(json.weather[0].icon); 
icon = icon.replace("\"",""); 
icon = icon.replace("\"",""); 
+0

感谢您的帮助! – JohnT