【问题标题】:currentArray.forEach is not a function (Fetch API)currentArray.forEach 不是函数(Fetch API)
【发布时间】:2018-07-16 10:16:57
【问题描述】:

我正在尝试查询一个 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 的方式有关,但我不确定。任何帮助将不胜感激。如果您想更好地查看,这是我的 codepen 的链接。

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

【问题讨论】:

  • resp.current 是一个对象而不是一个数组,看看 JSON 的结构。 { } 表示对象,[ ] 表示数组
  • resp.current 是一个对象

标签: javascript ajax xmlhttprequest fetch


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 2018-11-10
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2021-05-17
    • 2018-01-09
    相关资源
    最近更新 更多