【发布时间】:2019-08-29 13:28:46
【问题描述】:
我的代码有一个小问题。 基本上,我的 index.html 文件中有一个表单:
第 1 页的表格如下:
<form method="get" name="basicSearch" id = "basicSearch" action="page2.html">
<input name="location" type="text" class="BasicSearch" id="searchInput" placeholder="Location">
<button type= "submit" class="BasicSearch" id="searchBtn" placeholder="Search"></button>
</form>
对于这个表单,我想使用 OpenWeatherMap API 来获取一些天气数据。我的问题如下: 我想获取用户在表单中输入的内容,我认为可以通过使用来获取,例如:
var searchInput = document.getElementById("searchInput");
在这个变量中我可以存储位置。
而这个变量,我想在 javascript 代码中附加到从 API 获取数据的链接。
当用户输入,例如:纽约,然后按搜索,表单操作应该将他重定向到page2.html,在那里我可以显示天气数据。
如何在 page2 中显示天气数据,并从 page1 输入位置?我尝试了很多次,但没有运气。 下面是一些 Javascript 代码:
let units = 'metric';
let searchMethod = 'q';
let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");
if (searchButton) {
searchButton.addEventListener('click', () => {
let searchTerm = searchInput.value;
if (searchTerm)
searchWeather(searchTerm);
});
}
function searchWeather(searchTerm) {
fetch(`http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}`).then(result => {
return result.json();
}).then(result => {
init(result);
})
}
function init(resultFromServer){
let weatherDescriptionHeader = document.getElementById('weatherDescriptionHeader');
let temperatureElement = document.getElementById('temperature');
let humidityElement = document.getElementById('humidity');
let windSpeedElement = document.getElementById('windSpeed');
let cityHeader = document.getElementById('cityHeader');
let weatherIcon = document.getElementById('documentIconImg');
weatherIcon.src = 'http://openweathermap.org/img/w/' + resultFromServer.weather[0].icon + '.png';
let resultDescription = resultFromServer.weather[0].description;
weatherDescriptionHeader.innerText = resultDescription.charAt(0).toUpperCase() + resultDescription.slice(1);
temperatureElement.innerHTML = Math.floor(resultFromServer.main.temp) + '°' + " C";
windSpeedElement.innerHTML = 'Winds at ' + Math.floor(resultFromServer.wind.speed) + ' mph';
cityHeader.innerHTML = resultFromServer.name;
humidityElement.innerHTML = 'Humidity levels at ' + resultFromServer.main.humidity + '%';
}
这是一些应该获取天气数据的 javascript 代码。 然后,在 page2 中,我在 HTML 中有以下内容:
<div id = "weatherContainer">
<div id = "weatherDescription">
<h1 id = "cityHeader"></h1>
<div id= "weatherMain">
<div id = "temperature"></div>
<div id = "weatherDescriptionHeader"></div>
<div><img id = "documentIconImg"></div>
</div>
<hr>
<div id = "windSpeed" class = "bottom-details"></div>
<div id = "humidity" class = "bottom-details">></div>
</div>
</div>
我希望在 div 所在的 page2 中有天气数据。 有人可以给我一个建议吗? 谢谢!
【问题讨论】:
-
也显示你的服务器端代码。我认为没有服务器端代码是不可能的,除非你使用 SPA
-
您需要一些服务器端代码来获取 GET 变量
-
服务器端...类似于 REST?
-
你也可以在没有服务器端的情况下做到这一点@GabrielCretu
-
您的 page2 代码指的是 page1 页面中的元素...所以,这不起作用... page2 将加载
?location=whateverwaseteredbytheuser作为location.search...所以@ 987654328@ 将是第 1 页中输入的位置
标签: javascript html css