javascript - currentArray.forEach 不是函数(Fetch API)

标签 javascript ajax xmlhttprequest fetch

我正在尝试查询 URL 字符串并提取一些天气数据。我收到了回复,但出于某种原因,我无法提取数据。我收到一条错误提示 cur

const weatherForm = document.querySelector("#weather-form");
weatherForm.addEventListener("submit", fetchWeather);

function fetchWeather(e) {
  e.preventDefault();
  
  const searchTerm = document.querySelector(".search").value;
  fetch(`https://api.apixu.com/v1/current.json?key=c54944da22b147b48ec152033160205&q=${searchTerm}`)
  .then((response) => {return response.json(); })
  .then((resp => {
   // console.log(resp);
    let currentArray = resp.current;
    console.log(currentArray);
    showWeather(currentArray);
  }))
  .catch(err => console.log(err));
}

function showWeather(currentArray) {
  alert("Hello");
  const results = document.querySelector(".results");
  
  let output = '<div class="container">';
  currentArray.forEach((weatherData => {
    output += `
    <h2>${weatherData.feelslike_f}</h2>
`;
  }))
  document.querySelector(".results").innerHTML = output;
}
<form id="weather-form">
  <input type="text" class="search">
  <input type="submit" value="submit">
</form>
<div class="results"></div>

rentArray.forEach 不是函数。这是我的代码: 我认为这与我执行 let currentArray = resp.current 的方式有关,但我不确定。任何帮助将不胜感激。如果您想更好地了解,这里有一个指向我的代码笔的链接。

https://codepen.io/Brushel/pen/JBGGYp?editors=1011

最佳答案

API 只返回一个对象,而不是对象数组。修复 showWeather,使其仅访问对象的属性,而不是尝试遍历数组:

const weatherForm = document.querySelector("#weather-form");
weatherForm.addEventListener("submit", fetchWeather);

function fetchWeather(e) {
  e.preventDefault();
  
  const searchTerm = document.querySelector(".search").value;
  fetch(`https://api.apixu.com/v1/current.json?key=c54944da22b147b48ec152033160205&q=${searchTerm}`)
  .then((response) => {return response.json(); })
  .then((resp => {
   // console.log(resp);
    let currentArray = resp.current;
    // console.log(currentArray);
    showWeather(currentArray);
  }))
  .catch(err => console.log(err));
}

function showWeather(weatherData) {
  document.querySelector(".results").innerHTML = `
  <div class="container">
    <h2>${weatherData.feelslike_f}</h2>
  </div>
  `;
}
<form id="weather-form">
  <input type="text" class="search">
  <input type="submit" value="submit">
</form>
<div class="results"></div>

关于javascript - currentArray.forEach 不是函数(Fetch API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51353753/

相关文章:

javascript - 为什么我的正则表达式在 JavaScript 中不起作用? (它适用于 Java)

javascript - HTML5 幸运轮(午餐轮)

javascript 日期和 python 日期时间对象

javascript - 停止在 PHP AJAX MySQL 中重复 div 内容

javascript - XMLHttpRequest 中 TCP 握手究竟何时发生?

javascript - zeroclipboard 工作一半的时间

javascript - 简单的AJAX检索XML文件中的数据,在 ".responseXML"左右出错

jquery - Handlebars 预输入计数结果显示

google-apps-script - 如何使用 Google-apps-script 从延迟加载的网页(通过 API)抓取数据?

javascript - 如何使用 Google Drive 的 api 打开文件?