如何根据用户输入操作 API 端点地址

How to manipulate a API endpoint address based on user input

我正在研究一些 HTML 和 JavaScript,最终目标是创建一个显示当前天气的简单网站。我以前没有使用过 API,而且我对 JavaScript 的了解有限,所以这可能是一个非常糟糕的问题。我可以根据用户输入更改端点地址吗?

我写了一些显示简单表单的前端。

<section id="weather">
            <div id="nav">
                <div id="locate">
                    <div id="container">
                        <form action="index.js">
                            <label for="location">Location:</label>
                            <input type="text" id="location" name="location" required>
                            <input type="submit" value="Let's Go!">
                        </form>
                    </div>
                </div>
                <div id="output">
                    <div id="container">
                        <!-- Output of API -->

                    </div>
                </div>
            </div>
 </section>

我在想这可以 运行 一个 JavaScript 文件,它收集表单 HTML 文件的输入并做这样的事情:

const location = document.getElementById(location)
http://api.openweathermap.org/data/2.5/weather?q=${location}&APPID=API

我尝试编写一些程序来执行此操作,但由于我对 javascript 和 API 的了解有限,所以我总是失败。在我花很多时间之前,有人可以告诉我这是否可能吗? 顺便说一句,我已经设置了一个 API 键,但我没有显示它。

谢谢,

捷运

所以这只是一个非常冗长的方法,以便您可以理解每个步骤

第 1 步:首先您要访问输入元素:

const locationInput = document.getElementById("location");

第 2 步:然后您想获取该输入元素的值

const locationValue = locationInput.value;

第 3 步:然后您想在 URL

中使用该值

const url = http://api.openweathermap.org/data/2.5/weather?q=${locationValue}&APPID=API


function fetchAPIData() {
  const locationInput = document.getElementById('location');
  const locationValue = locationInput.value;
  const url = `http://api.openweathermap.org/data/2.5/weather?q=${locationValue}&APPID=API`
  // do the URL Request

}
document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('input[type=submit]').addEventListener('click', fetchAPIData);
});
<section id="weather">
  <div id="nav">
    <div id="locate">
      <div id="container">
        <form action="index.js">
          <label for="location">Location:</label>
          <input type="text" id="location" name="location" required>
          <input type="submit" value="Let's Go!">
        </form>
      </div>
    </div>
    <div id="output">
      <div id="container">
        <!-- Output of API -->
      </div>
    </div>
  </div>
</section>

更短的方法是:

const url = `http://api.openweathermap.org/data/2.5/weather?q=${document.querySelector("#location").value}&APPID=API`;