You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML页面展示API返回的全部JSON响应而非仅第一条

解决方法

要展示API返回的所有响应,你需要遍历整个响应数组并为每个条目生成对应的HTML,同时调整CSS避免元素重叠。以下是修改后的完整代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Weather Alerts</title>
    <script defer src="https://cdn.aerisapi.com/sdk/js/latest/aerisweather.min.js"></script>

    <style>
      #alerts {
        margin: 20px;
      }
      .weather-card {
        position: relative;
        display: inline-block;
        margin: 0 15px;
        width: 190px;
        height: 180px;
      }
      #alerts .tempicon {
        position: absolute;
        top: 5px;
        left: 10px;
        width: 170px;
        height: 170px;
      }
      #alerts .temptext {
        position: absolute;
        top: 55px;
        left: 30px;
        color: #ffffff;
        font-size: 50px;
        font-family: Arial, Helvetica, sans-serif;
        text-shadow: 2px 2px 5px black;
      }
    </style>
  </head>
  <body topmargin="0" leftmargin="0">
    <div id="alerts"></div>

    <script>
      window.onload = () => {
        const target = document.getElementById("alerts");
        const aeris = new AerisWeather("[CLIENT_ID]", "[CLIENT_SECRET]");
        const request = aeris.api().endpoint("observations/summary").place("minneapolis,mn").from("today");
        request.get().then((result) => {
          const periods = result.data;
          if (periods) {
            // 遍历所有响应条目,生成每个条目的HTML
            const html = periods.map(item => `
              <div class="weather-card">
                <img src="https://dakotaradar.org/newicons/temps/${item.periods[0].summary.temp.maxF}.png" class="tempicon">
                <div class="temptext">${item.periods[0].summary.temp.maxF}&#176;F</div>
              </div>
            `).join(''); // 将所有HTML片段拼接成一个字符串
            target.innerHTML = html;
          }
        });
      };
    </script>
  </body>
</html>

关键修改点:

  1. 遍历响应数组:使用Array.map()方法遍历periods数组中的每个条目,为每个条目生成对应的HTML片段,再通过join('')拼接成完整的HTML字符串,替代原代码中仅取第一个条目(periods[0])的逻辑。
  2. 添加容器避免重叠:新增.weather-card类作为每个天气条目的容器,设置为inline-block让条目横向排列,同时使用position: relative确保内部绝对定位的元素相对于容器定位,避免所有图标和文字重叠。
  3. 调整布局间距:为#alerts和.weather-card添加margin,让整体布局更美观。

内容的提问来源于stack exchange,提问作者Tater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:57:38