[英]How to get images searched from an input with an url API, using javascript and show to an html page?
我在一个html页面中创建了一个输入和一个按钮。 从那个输入我想“获取”文本并使用url API来搜索gif。 之后,我想将所有src图像复制到我的html页面以显示那里的GIF。
<!doctype html>
<html lang="en">
<head>
<title>Load gif and images</title>
<!--CSS -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Search for gifs</h1>
</header>
<!--Section with input for search-->
<section id="for-search">
<form action="javascript: main.js;" onsubmit="return searchgif()">
<input type="text" name="search" placeholder="type your text here" class="search" id="search">
<button class="submit">SUBMIT</button>
</form>
</section>
<!--END search section-->
<!--Section to display gifs for searched word-->
<section id="layout">
<div id="result">
<img id="gif"></img>
</div>
</section>
<!--END display section-->
<!-- JavaScript -->
<script src="main.js"></script>
</body>
</html>
//Main JS to search and display GIFS
function serchgif() {
var url = "https://b682nc9ec1.execute-api.us-east-1.amazonaws.com/dev/giphy/search?search=";
var searched = document.getElementById("search").value;
var api = url+searched;
var firstres = api.replace(/[|]|"/g, "");
var res = firstres.split(",");
var image = document.getElementById("gif")
var imgatt = document.createAttribute("src");
var i;
for (i = 0; i <= res.length; i++) {
imgatt.value = res[i];
image.setAttributeNode(imgatt);
}
}
我需要在代码中修改几个东西(小错误)。 但我设法实现了你想用fetch做的事情。
buttonEL = document.getElementById("button"); resultEL = document.getElementById("result"); buttonEL.addEventListener("click", searchgif); function searchgif() { var url = "https://b682nc9ec1.execute-api.us-east-1.amazonaws.com/dev/giphy/search?search="; var searched = document.getElementById("search").value; var api = url + searched; var firstres = api.replace(/[|]|"/g, ""); var res = firstres.split(","); fetch(res, {method: 'GET', headers: {Accept: 'application/json'} }) .then(function(response) { response.json() .then(function(text) { for ( let i = 0; i <= text.length - 1 ; i++) { var img = document.createElement("img"); img.setAttribute("src", text[i]); resultEL.appendChild(img); } }); }); }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Load gif and images</title> </head> <body> <header> <h1>Search for gifs</h1> </header> <!--Section with input for search--> <section id="for-search"> <form> <input type="text" name="search" placeholder="type your text here" class="search" id="search"> </form> <button id="button">SUBMIT</button> </section> <!--END search section--> <!--Section to display gifs for searched word--> <section id="layout"> <div id="result"> </div> </section> <!--END display section--> </body> </html>
请享用 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.