我正在尝试从输入元素获取城市名称,然后从API获取城市的天气信息和时区信息。 但是我无法在该函数中获取json对象,但它在函数外部工作。 任何人都可以帮助我吗?
var d = "Lisbon";
$(document).ready(function() {
$("#button").click(function() {
d = document.getElementById("input").value;
$(document).ready(function myfunction() {
$.getJSON('http://api.openweathermap.org/data/2.5/weather?APPID=11d324c05e02e308c1c9eb8d8041b143&q=' + d + '&units=metric', function(data) {
document.getElementById("city").innerHTML = data.name + ", " + data.sys.country;
document.getElementById("wind").innerHTML = data.wind.speed + " m/s ";
document.getElementById("cloudiness").innerHTML = data.weather[0].description;
document.getElementById("pressure").innerHTML = data.main.pressure + " hpa";
document.getElementById("humidity").innerHTML = data.main.humidity + " %";
document.getElementById("coord").innerHTML = "[ " + data.coord.lat + ", " + data.coord.lon + " ]";
document.getElementById("temperature").innerHTML = data.main.temp + "°C";
document.getElementById("icon").innerHTML = "<img src=http://openweathermap.org/img/w/" + data.weather[0].icon + ".png" + ">";
console.log(data);
(function() {
$.getJSON("http://api.geonames.org/timezoneJSON?" + "lat=" + data.coord.lat + "&" + "lng=" + data.coord.lon + "&username=hrrs", function(data) {
document.getElementById("time").innerHTML = data.time;
document.getElementById("timeCity").innerHTML = data.timezoneId;
document.getElementById("country").innerHTML = data.countryName;
document.getElementById("sunrise").innerHTML = data.sunrise;
document.getElementById("sunset").innerHTML = data.sunset;
console.log(data);
});
})();
});
document.getElementById("slayt").innerHTML = '<iframe src="http://www.panoramio.com/wapi/template/slideshow.html?tag=' + d + '&width=1920&height=500&" frameborder="0" width="1920" height="500" scrolling="no" marginwidth="0" marginheight="0"></iframe>';
})();
});
});
答案 0 :(得分:0)
这是你想要达到的目标吗? http://jsfiddle.net/wnunhhac/
<input type="text" id="inputCity" value="Zurich"/>
<input type="button" id="start" value="Go" />
<br />
<span id="city">click go</span>
$(document).ready(function() {
$("#start").click(function() {
var d = $("#inputCity").val();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?APPID=11d324c05e02e308c1c9eb8d8041b143&q=' + d + '&units=metric', function(data) {
$("#city").html(data.name);
});
});
});
如果城市无效,则API会返回未找到的状态代码404。所以你应该编写适当的共鸣。
if (data.cod === "404") {
// Api could not find city
return;
}
此外,我将按钮类型更改为&#34;按钮&#34;而不是&#34;提交&#34;
<button type="button" id="button" class="btn btn-default">