首页 > 解决方案 > 如何在不刷新页面的情况下获取?

问题描述

好的,我最近开始学习异步 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>

标签: javascriptapiasynchronous

解决方案


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

 <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>

推荐阅读