如何在不刷新页面的情况下获取?

时间:2021-05-26 04:48:26

标签: javascript api asynchronous

好吧,我最近开始学习异步 JS 和 API 以及 fetch,我只是创建一个小项目用于练习,我想再添加 2 个功能

  1. 我想添加一个按钮,当点击该按钮而不刷新页面时,会为我们提供一个新的 GIF。

  2. 我们可以使用该栏找到的 GIF 搜索栏。

这是我的代码:

<body>
  <img src="#" />
  <button>New Giffy</button>
  <script>
    const img = document.querySelector('img');
    const btn = document.querySelector('button');

    fetch(
        `https://api.giphy.com/v1/gifs/translate?api_key=pH9WHztAm5Yt9v5VAziRzXhOBvblWf6m&s=akatsuki`, {
          mode: 'cors'
        }
      )
      .then((response) => {
        return response.json();
      })
      .then((response) => {
        img.src = response.data.images.original.url;
      });
  </script>
</body>

2 个答案:

答案 0 :(得分:1)

这是非常直接的事情。但我会帮助你。

 <body>
    <img src="#" />
    <button onclick="newGif()">New Giffy</button>
    <script>
      const img = document.querySelector('img');
      const btn = document.querySelector('button');
      function newGif(){
        fetch(`https://api.giphy.com/v1/gifs/translate?api_key=pH9WHztAm5Yt9v5VAziRzXhOBvblWf6m&s=akatsuki`,{mode:'cors'})
        .then((response) => response.json())
        .then((response) => {
          img.src = response.data.images.original.url;
        });
      }
      newGif() //This is so a new gif is loaded as soon as the page loads
    </script>
  </body>

答案 1 :(得分:1)

你可以在按钮上提供onClick,它会调用下面代码中定义的函数或参考fiddle

<body>
  <input type="text" placeholder="search here..." id="searchField" value="akatsuki">
  <button onClick="onGifClick()">New Giffy</button><br>
  <img src="#" />
  <script>
    function onGifClick() {
      const search = document.querySelector('#searchField');
      const img = document.querySelector('img');
      const btn = document.querySelector('button');
      debugger;
      fetch(
          `https://api.giphy.com/v1/gifs/translate?api_key=pH9WHztAm5Yt9v5VAziRzXhOBvblWf6m&s=` + search.value, {
            mode: 'cors'
          }
        )
        .then((response) => {
          return response.json();
        })
        .then((response) => {
          img.src = response.data.images.original.url;
        });
    }
    onGifClick();
  </script>
</body>