【发布时间】: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 的链接。
【问题讨论】:
-
resp.current是一个对象而不是一个数组,看看 JSON 的结构。{ }表示对象,[ ]表示数组 -
resp.current是一个对象
标签: javascript ajax xmlhttprequest fetch