这就是我的网页:http://prntscr.com/dg6dmm和我的codepen链接:http://codepen.io/johnthorlby/pen/dOmaEr
我想从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 :(得分:0)
Weather是JSON中的一个数组,您需要正确地从中提取数据。此外,您的输出字符串有&#34; &#34;围绕它,所以我们需要删除它们。
var icon = JSON.stringify(json.weather[0].icon);
icon = icon.replace("\"","");
icon = icon.replace("\"","");