简体   繁体   中英

How to fix Form action with method get

I have a small issues with my code. Basically, I have a form in my index.html file:

The form from page 1 is the following:

<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>

For this form, I want to use OpenWeatherMap API in order to get some weather data. My problem is the following: I want to get what the user inputs in the form, which I think I can get by using, for example:

var searchInput = document.getElementById("searchInput");

In this variable I can store the location. And this variable, I want to append to the link that does fetch the data from the API, in the javascript code. When the user inputs, for example: New York, and press Search, the form action should redirect him to page2.html , where there I can show the weather data.

How can I show that weather data in the page2, with the location input from page1? I tried many times but no luck. Some Javascript code down below:

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) + '&#176' + " C";
    windSpeedElement.innerHTML = 'Winds at ' + Math.floor(resultFromServer.wind.speed) + ' mph';
    cityHeader.innerHTML = resultFromServer.name;
    humidityElement.innerHTML = 'Humidity levels at ' + resultFromServer.main.humidity + '%';
}

That is some javascript code which should get the weather data. Then, in page2, I have the following in 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>

I expected to have the weather data in page2, where the divs are. Can somebody give me an advice, please? Thank you!

Since the form in page1 doesn't exist in page 2, remove

let searchButton = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");

if (searchButton) {
    searchButton.addEventListener('click', () => {
        let searchTerm = searchInput.value;
        if (searchTerm)
            searchWeather(searchTerm);
    });
}

instead put

ley searchTerm = new URLSearchParams(location.search).get('location');
searchWeather(searchTerm);

Explanation

When the page 1 form is submitted, it will load page2 like

page2.html?location=xxxx

where xxxx is the value of the <input name='location' ...

location.search will be ?location=xxxx

URLSearchParams makes dealing with these (when you have more than one especially) easier than the old method of splitting/decoding/jumping through hoops

We can simply just submit the form and get the current form input from url on page2.html

<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">Search</button>

</form>

And on the load of page2.html (before your ajax call), we can get the 'searchInput' (location) from URL by following:

<script>
   let params = (new URL(document.location)).searchParams;
   var searchInput= params.get('location');
</script>

Now, we can use 'searchInput' param for your api call and fetch the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM