为了账号安全,请及时绑定邮箱和手机立即绑定

将浏览器中的搜索输入到 API get 请求

将浏览器中的搜索输入到 API get 请求

慕妹3242003 2023-10-14 15:59:17
我正在做一个家庭作业项目,我需要创建一个搜索,我需要将该搜索插入到 API 请求权限中,并让该 API 返回与该搜索相关的 Gif URL。我有搜索事件监听器的代码,还有 API get 请求的代码,我遇到的麻烦是让它们一起工作。当我注释掉一段代码时,独立的代码将按预期工作。我正在尝试将搜索 URL 打印到控制台,只是为了测试以确保我收到 URL。最后,我会将其附加到 DOM,但现在我只专注于从 API 获取 URL。任何意见都会受到赞赏。<!DOCTYPE html><html>  <head>    <meta charset="UTF-8" />    <title>Giphy Party!</title>    <link      rel="stylesheet"      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"    />  </head>  <body>    <div class="container text-center">      <h1>The Giphy Party!!!!!</h1>      <h2>It is Party Time!!!!!</h2>    </div>    <form class="gform">      <label for="search">        <input id="searchInput" type="text" />      </label>      <button>Search Gif</button>      <button>Remove Gifs</button>    </form>    <div class="container"><img id="img" src=""" alt="" /></div>    <script      src="https://code.jquery.com/jquery-3.5.1.min.js"      integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="      crossorigin="anonymous"    ></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>    <script src="https://unpkg.com/axios/dist/axios.js"></script>    <script src="app.js"></script>  </body></html>'''let searchInput = document.getElementById("searchInput");document.querySelector("form.gform").addEventListener("submit", function (e) {  e.preventDefault();  console.log(searchInput.value);});let randomIndex = Math.floor(Math.random() * 10);async function getGif() {  const res = await axios.get("https://api.giphy.com/v1/gifs/search", {    params: {      api_key: "tGZu4GXgLVVp0VTINvh66xcmIfJBPqoP",      q: searchInput,    },  });  console.log(res.data.data[randomIndex].url);}getGif();'''
查看完整描述

1 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

您在提交表单之前调用 getGif() 函数。事件侦听器不是同步事件。要解决此问题,您可以将其移至事件侦听器块中:


let searchInput = document.getElementById("searchInput");

document.querySelector("form.gform").addEventListener("submit", function (e) {

  e.preventDefault();

  console.log(searchInput.value);

  getGif(); // move it up here. now it will work.

});



let randomIndex = Math.floor(Math.random() * 10);



async function getGif() {

  const res = await axios.get("https://api.giphy.com/v1/gifs/search", {

    params: {

      api_key: "tGZu4GXgLVVp0VTINvh66xcmIfJBPqoP",

      q: searchInput,

    },

  });

  console.log(res.data.data[randomIndex].url);

}


查看完整回答
反对 回复 2023-10-14
  • 1 回答
  • 0 关注
  • 53 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信