使用 Fetch Api 进行 Giphy 搜索

mKe01010101

在使用 Api 时,我很新。我正在尝试查询 URL 字符串并返回一些 Gif。

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))从 fetch 中删除并且只删除console.log数据,它将返回我想要的搜索结果。但是,当我尝试映射到 gif"data.images.fixed_width.url" 时,我收到控制台错误“Uncaught (in promise) TypeError: Cannot read property 'fixed_width' of undefined”fetch.then.then.data

任何帮助或朝正确方向推动都会很棒!谢谢!另外,如果您想查看演示,可以在此处查看:https : //codepen.io/Brushel/pen/jKgEXO?editors=1010

优素福BH

您的代码有几个问题。

API 的响应是一个对象,在这个对象中有一个data数组,这个数组中的每个元素都是关于每个 gif 的信息。

尝试:

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>

我希望这将有所帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章