尝试在具有输入值的API上搜索而不刷新页面

  • 本文关键字:搜索 刷新 API javascript html
  • 更新时间 :
  • 英文 :


我试图使我的代码采取输入值,当我单击搜索按钮,并使用该值在gifphy API中搜索,而不刷新页面。我现在得到一个类型错误:

TypeError:undefined不是一个对象(求值subjectData.data.images.original)。

如有任何帮助,不胜感激

const img = document.querySelector('img');
const inputValue = document.getElementById('input').value;
const button = document.getElementById('button');
button.addEventListener('click', getGif)
async function getGif() {
try {
const response = await fetch(`https://api.giphy.com/v1/gifs/translate?api_key=MYKEY&s=${inputValue}`, {
mode: 'cors'
});
const subjectData = await response.json();
img.src = subjectData.data.images.original.url;
} catch (error) {
console.log(error);
}
}
getGif();
<input type="text" placeholder="search" id='input'>
<button id='button'>Search</button>
<img src="#" />

data: [] (0)

meta: {status: 200, msg: "OK", response_id: "095528aed75dc51ed9ac4439ceac93400de8f48c"}

我似乎已经让它在我这端工作了。我交换了你的async/await只是取回,但它工作得很好。让我知道,如果你能够与此工作或迁移到您现有的设置。如果你愿意,我可以试着把它重新格式化回你的async/awasit设置。

const img = document.querySelector('img');
const button = document.getElementById('button');
button.addEventListener('click', getGif);
const apiKey = document.getElementById('apikey').value;
const searchField = document.getElementById('input');
function getGif() {
return fetch(`https://api.giphy.com/v1/gifs/translate?api_key=${apiKey}&s=${searchField.value}`, { mode: 'cors' }).then((response) => response.json()).then(data => img.src = (data.data?.images?.original?.url || "#"));
}
img {
max-width: 250px;
max-height: 150px;
}
img[src="#"] {
display: none;
}
<input type="text" placeholder="API Key" id="apikey">
<input type="text" placeholder="Search…" id="input">
<button id='button'>Search</button>
<img src="#" />

最新更新