【发布时间】:2016-08-17 14:14:26
【问题描述】:
我创建了一些代码,在您输入城市和国家/地区后,这些代码应该会显示来自 openweather API 的一些数据。点击提交按钮后,它目前什么都不做。
这是我的 HTML 文件:Index.html
<head>
<title>Open Weather API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="mainWeather.js"></script>
</head>
<body>
<div id="userArea">
<div id="stateWrapper">
<input type="text" id="cityInput" placeholder="Enter a State"/>
</div>
<br/>
<div id="countryWrapper">
<input type="text" id="countryInput" placeholder="Enter a Country"/>
</div>
<br/>
<div id="buttonArea">
<input type="submit" id="submitWeather"/>
</div>
</div>
<!- USED TO SHOW RESULT -->
<div id="weatherWrapper">
</div>
</body>
在我的代码中,我已将“密钥”更改为我的实际密钥
这是我的 JavaScript 文件:mainWeather.js
var mainWeather = {
init: function () {
$("#submitWeather").click(function () {
return mainWeather.getWeather();
});
},
getWeather: function () {
$.get('http://api.openweathermap.org/data/2.5/weather?q=' + $("#cityInput").val() + "," + $("#countryInput").val() + "Key", function (data) {
var json = {
json: JSON.stringify(data),
delay: 1
};
echo(json);
});
},
//Prints result from the weatherapi, receiving as param an object
createWeatherWidg: function (data) {
return "<div class='pressure'> <p>Temperature: " + (data.main.temp - 273.15).toFixed(2) + " C</p></div>" +
"<div class='description'> <p>Title: " + data.weather[0].main + "</p></div>" +
"<div class='description'> <p>Description: " + data.weather[0].description + "</p></div>" +
"<div class='wind'> <p>Wind Speed: " + data.wind.speed + "</p></div>" +
"<div class='humidity'> <p>Humidity: " + data.main.humidity + "%</p></div>" +
"<div class='pressure'> <p>Pressure: " + data.main.pressure + " hpa</p></div>";
}
};
var echo = function (dataPass) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: dataPass,
cache: false,
success: function (json) {
var wrapper = $("#weatherWrapper");
wrapper.empty();
wrapper.append("<div class='city'> <p>Place: " + json.name + ", " + json.sys.country + "</p></div>");
wrapper.append(mainWeather.createWeatherWidg(json));
}
});
};
mainWeather.init();
我似乎无法弄清楚为什么它不起作用,这两个文件在同一个文件夹中。
【问题讨论】:
-
控制台有什么错误吗?你说这两个文件在同一个文件夹中,但在 HTML 中你的
<script type="text/javascript" src="resources/js/mainWeather.js"></script>暗示它应该在一个名为“/resources/js”的子文件夹中 -
哦,对不起,我确实在那个文件夹中有它,但我移动了它,忘记更改代码了哎呀!我改了代码还是不行,控制台也没有错误
标签: javascript html json ajax openweathermap