【问题标题】:Javascript - loop through results from API call to JSON, and print in HTMLJavascript - 循环从 API 调用到 JSON 的结果,并以 HTML 格式打印
【发布时间】:2021-03-05 02:25:21
【问题描述】:

我正在使用 openweathermap.org API,并且正在使用 javascript 来获取数据,然后发布到 HTML。我有两个 javascript 函数。获取当前天气的一个功能非常有效 - 第二个功能是拉 5 天预报。我已经到了可以提取数据的地步,但是我需要遍历该数据并发布到 HTML。函数如下:

function getForecast() {
    let forecast_icon = document.getElementById("forecast_icon");
    let forecast_temperature = document.getElementById("forecast_temperature");

    let api = "https://api.openweathermap.org/data/2.5/weather";
    let apiKey = "API KEY";

    location.innerHTML = "Locating...";

    navigator.geolocation.getCurrentPosition(success, error);

    function success(position) {
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;

        let url = api + "?lat=" + latitude + "&lon=" + longitude + "&appid=" + apiKey + "&units=imperial";

        fetch(url)
            .then(response => response.json())
            .then(forecast => {
                console.log(forecast);

                let temp = forecast.main.temp;
                forecast_temperature.innerHTML = Math.round(temp) + "°F";
                let icon = forecast.weather[0].icon;
                forecast_icon.innerHTML = '<img src="http://openweathermap.org/img/wn/' + icon + ".png" + '"/>';
            });
    }

    function error() {
        location.innerHTML = "Unable to retrieve your location";
    }
}

getForecast();

这是 HTML - 非常简单:

<ul>
  <li>
    <div id='forecast_icon'></div>
    <div class='temperature-sensor-day' id='forecast_temperature'></div>
  </li>
</ul>

我不确定如何遍历数据并将每个结果发布到 HTML。我会继续搜索,但希望得到一些指导。

编辑:

我需要遍历 API 调用的输出并将该数据发布到上面显示的 HTML 中。

我尝试使用“承诺”。我在搜索中看到了这个:

for (url in urls){
    time = getData(urls[url])
    console.log(time)
    ttTimes.push(time)
};

我尝试替换我的值,但由于这个使用了两个 url,我无法弄清楚如何让它工作。

我还看到了不同类型的循环,所以我对最好的方法感到困惑。

下面是它的外观图片。您可以看到五天中只有一天在填充。希望这有助于可视化问题。

【问题讨论】:

  • 您没有从 API 调用中提供样本数据,这使得您很难猜测您需要帮助循环的数据结构。
  • 您没有显示任何尝试单步执行数据的尝试,并且可能尝试对其进行编辑。您的代码调用了 api。我正在使用手机,但一个好的开始是查看地图,对于 dontenv,我在遇到问题时发布了一个关于它的问题:stackoverflow.com/questions/57213162/…
  • 最好把它贴进去并解释一下,因为现在它完全不见了。
  • 我在这里删除和/或编辑了一堆 cmets 以删除对投票的讨论。 请不要在 cmets 中讨论投票。投票是匿名的,没有人会给出投票的理由,无论是赞成还是反对。
  • 坦率地说,史蒂夫,关于你可以在哪里与我聊天的问题的答案是“无处”。这不是真正值得辩论或讨论的事情。这只是网站政策。你说“无缘无故投票”,但事实并非如此。反对者有一个理由。他们只是选择不发表评论。那是另一回事。原因在向下投票箭头的工具提示中给出。我同意,建设性的批评是受欢迎的,但它是可选的。抨击反对者是不受欢迎的。另见:the relevant FAQ on Meta

标签: javascript json function loops openweathermap


【解决方案1】:

你就在那里。您要查找的数据位于 API 响应 documented here 的 list 数组中。您只需遍历 list 数组,为您希望显示的每个数据创建 HTML 元素,并在执行过程中附加到 DOM。

请注意,我正在动态制作 HTML 元素以将数据插入其中,因此您不需要 HTML 文档中的当前元素。

fetch(url)
    .then(response => response.json())
    .then(forecast => {

        // For each day, we'll loop through and add it to the DOM:
        forecast.list.forEach(day => {

            // Create a new element to hold each day's data in the DOM:
            const dayContainer = document.createElement('div')

            // Create an element to hold the temp data:
            const temp = day.main.temp;
            const tempElem = document.createElement('div')
            tempElem.innerText = Math.round(temp) + '°F'
            dayContainer.appendChild(tempElem)

            // Create an image element to hold the icon:
            const icon = day.weather[0].icon;
            const iconElem = document.createElement('img')
            iconElem.src = 'http://openweathermap.org/img/wn/' + icon + '.png'
            dayContainer.appendChild(iconElem)

            // Add the result to the DOM:
            document.body.appendChild(dayContainer)
        })
    })

请注意,最后我将附加到document.body。您可能想要附加到不同的元素,在 DOM 的层次结构中更深。

【讨论】:

  • 我有一个天气本身的功能 - 看起来像这样。另一个返回 5 天预测。 fetch(url) .then(response => response.json()) .then(data => { console.log(data); let temp = data.main.temp; temperature.innerHTML = Math.round(temp) + “°”;weather_icon.innerHTML = 'openweathermap.org/img/wn' + 图标 + "@2x.png" + '"/>';location.innerHTML = data.name;description.innerHTML = data.weather[ 0].main; });
  • 我有点明白这是怎么回事 - 但是 - 只有一个 URL。那个 URL 拉取数据。 URL 在这里形成: let url = api + "?lat=" + latitude + "&lon=" + longitude + "&appid=" + apiKey + "&units=imperial"; - 你是说我需要多个 URL?
  • 我已更新我的答案以说明您的问题的更新。 Promise 非常棒,但也有很多需要突破的地方。一旦你熟悉了Promise.all 和.thens,你应该看看async and await 语法。它消除了由大量 .thens 引起的大量嵌套,并将所有内容保持在同一个高级范围内。
  • 啊——也许不是。我以为您是在说您需要查询多个 URL。浏览 openweathermap API,我看不到您可以在单个响应中返回多天。你看到这个了吗,如果看到了,你能链接到它吗?
  • 当然 - 这是我正在使用的 API:openweathermap.org/forecast5 - 我使用 PHP 进行了这项工作,但它需要一个表单才能使其工作,而且很混乱。我认为 javascript 会更干净!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-12
  • 1970-01-01
  • 2020-12-03
  • 2017-03-10
  • 2020-07-15
  • 1970-01-01
  • 2022-08-06
相关资源
最近更新 更多