javascript - 如何在不刷新页面的情况下获取?
问题描述
好的,我最近开始学习异步 JS 和 API 和 fetch,我只是创建了一个小项目来练习,我想向它添加另外 2 个功能
我想添加一个按钮,当点击它而不刷新页面时,会给我们一个新的 GIF。
我们可以使用该栏找到 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>
解决方案
这是非常直接的事情。但我会帮助你。
<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>
推荐阅读
- sql - 无法将 FileStream 文件组删除或重新附加到 SQL Server 数据库
- thread-safety - 带有 Bays-Durham 的 L'Ecuyer 随机数生成器
- javascript - 在表格中以特定标题名称的顺序显示对象数组
- css - 在 Firefox 中显示 flex 没有达到 100% 的高度
- javascript - 如何将变量从 javascript 传递到 django 视图
- python - 如何将参数传递给 Airflow on_success_callback 和 on_failure_callback
- f# - 是否可以要求静态解析的类型参数是泛型类型?
- pipeline - 如何在 ADF 中动态获取管道名称?
- web-services - 任何人都可以解释一下webservices的用途是什么
- javascript - 根据权限更改按钮状态反应本机