微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

显示来自 Javascript Fetch API 的数据 - 问题

如何解决显示来自 Javascript Fetch API 的数据 - 问题

我是在 JavaScript 中使用 API 的新手。我希望获得用户放入站点(城市名称)上的框中的输入并获取 API,以检索该城市的温度。到目前为止,我有以下内容获取 API。但是我对如何实际获取该数据并显示它有点迷茫。我将如何获得“数据”?我只是不习惯在 Javascript 中使用 API 并希望了解更多信息。

js 文件

public static IntNode addBefore(IntNode front,int target,int newItem) {

    while(front.next != null) {
        if(front.next.data == target) {
            IntNode neww = new IntNode(newItem,front.next);
            front.next = neww;
            return neww;
        }
        front = front.next;
    }
    return null;
}

然后我有这个。 searchUser 只是代表用户输入的位置:

function hi() {

  function temperature(input) {
  const myKey = "Hidden_for_privacy";
  const api = `https://api.openweathermap.org/data/2.5/weather? 
  q=${input}&lang=en&&appid=${myKey}&units=metric`;

  fetch(api)
  .then(function(response){
      let data = response.json();
      console.log(data);
      return data;
  })

相关 HTML:

  const search = document.getElementById("searchUser");
  const button = document.getElementById("submit");
  button.addEventListener("click",() => {
    const currentVal = search.value;

解决方法

我认为在您可以在屏幕上显示数据之前,您遇到了一些语法错误。我建议首先专注于 JS 实现,以确保您成功获取数据并将其加载到控制台。例如,JS 中的闭包可能会导致问题。 hi 函数正在创建一个闭包,然后您将输入的参数传递到其中的函数中,但没有可获取的局部变量。

也许尝试这样的事情来启动并查看它记录的内容:

function getTemperature() {
  const myKey = "Hidden_for_privacy";
  const api = `https://api.openweathermap.org/data/2.5/weather? 
  q=${input}&lang=en&&appid=${myKey}&units=metric`;

  // .json returns a promise so you need to use .then to get the data from it synchronously
  fetch(api)
    .then((response) => response.json())
    .then(data => console.log(data))
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。