当涉及到使用Api时,我非常新,我试图查询URL字符串并返回一些Gifs。
const gifForm = document.querySelector("#gif-form");
gifForm.addEventListener("submit", fetchGiphs);
function fetchGiphs(e) {
e.preventDefault();
const searchTerm = document.querySelector("#search").value;
fetch(`https://api.giphy.com/v1/gifs/search?&q=${searchTerm}&limit=100&api_key=3mIxmBZUIIPyb8R69gtxaW8Hsh74dFKV`)
.then((response) => {return response.json(); })
.then(data => showGiphs(data.images.fixed_width.url))
.then(err => console.log(err));
}
function showGiphs(fixed_width) {
const results = document.querySelector("#results");
let output = '<div class="container">';
fixed_width.forEach((url) => {
console.log(url);
output += `
<img src="${data.images.original.fixed_width_url}"/>
`;
});
document.getElementById('results').innerHTML = output;
}<form id="gif-form">
<input type="text" id="search">
<input type="submit" value="find">
</form>
<div id="results"></div>
如果我从提取中删除.then(data => showGiphs(data.images.fixed_width.url))并只对数据进行console.log,它将返回我想要的搜索结果。然而,当我试图映射到gif"data.images.fixed_width.url“时,我在fetch.then.then.data上得到了一个控制台错误:"Uncaught (承诺) TypeError:无法读取未定义的属性'fixed_width‘”。
任何帮助或推动正确的方向将是令人敬畏的!谢谢!另外,如果您想要查看演示,可以在这里查看:https://codepen.io/Brushel/pen/jKgEXO?editors=1010
发布于 2018-07-07 11:44:32
您的代码有几个问题。
API的响应是一个对象,在这个对象中有data数组,这个数组中的每个元素都是关于每个gif的信息。
Try:
const gifForm = document.querySelector("#gif-form");
gifForm.addEventListener("submit", fetchGiphs);
function fetchGiphs(e) {
e.preventDefault();
const searchTerm = document.querySelector(".search").value;
fetch(`https://api.giphy.com/v1/gifs/search?&q=${searchTerm}&limit=100&api_key=3mIxmBZUIIPyb8R69gtxaW8Hsh74dFKV`)
.then((response) => {return response.json(); })
.then((resp => {
// Here we get the data array from the response object
let dataArray = resp.data
// We pass the array to showGiphs function
showGiphs(dataArray);
}))
.catch(err => console.log(err)); // We use catch method for Error handling
}
function showGiphs(dataArray) {
const results = document.querySelector(".results");
let output = '<div class="container">';
dataArray.forEach((imgData) => {
output += `
<img src="${imgData.images.fixed_width.url}"/>
`;
});
document.querySelector('.results').innerHTML = output;
} <form id="gif-form">
<input type="text" class="search">
<input type="submit" value="find">
</form>
<div class="results"></div>
我希望这能帮上忙。
发布于 2018-07-07 02:57:58
响应具有一个data属性,它是一个数组。如果您想要该数组中的第一个GIF,那应该是这样的:data.data[0].images.fixed_width.url。所以整行都是.then(data => showGiphs(data.data[0].images.fixed_width.url))。
https://stackoverflow.com/questions/51219503
复制相似问题