慕妹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條經驗 獲得超8個贊
您在提交表單之前調用 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);
}
添加回答
舉報
0/150
提交
取消