목차
예시
const url = "https://picsum.photos/v2/list?page=2&limit=5";
fetch( url )
.then( res => res.json() )
.then( data => makeList(data) )
.catch( console.log );
function makeList( data ) {
data.forEach( item => {
const tagImg = document.createElement( 'img' );
tagImg.setAttribute( 'src', item.download_url );
tagImg.style.width = 200 + 'px';
tagImg.style.height = 200 + 'px';
document.body.appendChild( tagImg );
});
}
예시를 사용해, 조건과 같이 출력
조건 :
- url을 입력받아 버튼을 누르면 출력
- 사진이 출력된 상태에서 버튼을 누르면 출력된 사진이 삭제
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax</title>
<link rel="stylesheet" href="./43_Ajax.css">
</head>
<body>
<form action="43_Ajax.html">
<input type="text" placeholder="url 입력" id="url_input">
<button type="button" id="btn">API 실행</button>
</form>
<div id="div_img"></div>
<script src="./43_Ajax.js"></script>
</body>
</html>
// https://picsum.photos
// const url = "https://picsum.photos/v2/list?page=1&limit=5";
const div = document.getElementById( "div_img" );
const btn = document.getElementById( "btn" );
const imgTag = document.getElementsByTagName( "img" );
let url = "";
function removeImg() {
div.replaceChildren();
}
function getVal() {
url = document.getElementById( "url_input" ).value;
fetch( url )
.then( res => res.json() )
.then( data => makeList( data ) )
.catch( console.log );
}
function makeList( data ) {
data.forEach( item => {
const tagImg = document.createElement( "img" );
tagImg.setAttribute( "src", item.download_url );
div.appendChild( tagImg );
});
}
function toggle() {
if( url === "" ) {
getVal();
} else {
removeImg();
url = "";
}
}
btn.addEventListener( "click", () => toggle() );
Github
'JavaScript > JavaScript_TEST' 카테고리의 다른 글
promise_TEST (0) | 2023.05.09 |
---|---|
timer_TEST (0) | 2023.05.08 |
DOM_TEST (0) | 2023.05.05 |
date_TEST (0) | 2023.05.05 |
math_TEST (0) | 2023.05.05 |