gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:30:00 26 4
gpt4 key购买 nike

我正在尝试查询 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com