AJAX 갤러리
jQuery load()는 특정 URL의 리소스를 요청하고, 응답을 HTML로 변환하여 지정된 DOM 요소에 로드합니다.
💡 ajax (Asynchronous JavaScript and XML) (에이싱크러너스 자바스크립트 앤 xml) 비동기 방식의 자바스크립트와 xml
💡Ajax(Asynchronous Javascript and XML)는 클라이언트 가 비동기방식으로 자바스크립트를 이용하여 > 화면 전환 없이 서버측에 자료(XML,HTML,JSON,텍스트…)를 요청할때 사용
- 동기방식: 서버에 신호를 보냈을때 응답이 돌아와야 다음 동작을 수행
- 비동기방식: 신호를 보냈을때 응답여부와 상관없이 다음 동작 실행
<!DOCTYPE html><html lang="ko"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="1.css" /> </head>
<body> <div class="row"> <ul> <li><img src="http://qwerew.cafe24.com/images/1.jpg" data-src="gallery/1.html" class="pic" /></li> <li><img src="http://qwerew.cafe24.com/images/2.jpg" data-src="gallery/2.html" class="pic" /></li> <li><img src="http://qwerew.cafe24.com/images/3.jpg" data-src="gallery/3.html" class="pic" /></li> </ul> </div> <div id="lightbox"> <div id="lightboxImage"></div> </div> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script src="jq.js"></script> </body></html>.row { width: 420px; margin: 0 auto;}
.row ul { list-style: none; margin: 0; padding: 0;}
.row ul li { display: inline-table; width: 30%;}.row ul li img { width: 100%;}/* 라이트 박스 스타일 */#lightbox { position: fixed; width: 100%;
height: 100%; background-color: rgba(0, 0, 0, 0.7); top: 0; left: 0; display: none;}
/* 라이트 박스 안의 이미지 */#lightbox { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 5px solid #eee; overflow: hidden; z-index: 100;}
.all_scrollFixed { overflow: hidden;}.all_scrollFixed::before { position: fixed; top: 0; left: 50%; width: 1000%; height: 10000%; background-color: rgba(0, 0, 0, 0.2); transform: translateX(-50%); content: ''; z-index: 95;}#lightboxImage { left: 50%; transform: translateX(-50%); position: fixed; width: 80%; height: 80vh; overflow-y: auto; top: 100px;}const pics = $('.pic');const lightbox = $('#lightbox');const lightboxImage = $('#lightboxImage');
pics.on('click', function () { const bigLocation = $(this).attr('data-src'); lightboxImage.load(bigLocation); $('html').addClass('all_scrollFixed'); lightbox.css('display', 'block');});
lightbox.on('click', function () { lightbox.css('display', 'none'); $('html').removeClass('all_scrollFixed');});const pics = document.getElementsByClassName('pic'); // .pic인 요소들을 가져와 pics 라는 변수에 저장. querySelectorAll(".pic")도 가능const lightbox = document.getElementById('lightbox'); // 라이트 박스. querySelector("#lightbox")도 가능const lightboxImage = document.getElementById('lightboxImage'); // 라이트 박스 안의 이미지. querySelector("#lightboxImage")도 가능
for (i = 0; i < pics.length; i++) { pics[i].addEventListener('click', showLightbox);}
async function showLightbox() { const bigLocation = this.getAttribute('data-src'); // bigLocation = this.data-src; 도 가능. try { const response = await fetch(bigLocation); console.log(response);//응답결과확인 if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const htmlContent = await response.text(); lightboxImage.innerHTML = htmlContent; lightbox.style.display = 'block'; // 라이트박스 이미지를 화면에 표시 document.querySelector('html').style.overflow = 'hidden'; } catch (error) { console.log(error); }}
lightbox.onclick = function () { //click 이벤트가 발생했을 때 실행할 함수 선언 lightbox.style.display = 'none'; // lightbox 요소를 화면에서 감춤 document.querySelector('html').style.overflow = 'visible';};#9: 이 함수는 비동기적으로 작동하며, async 키워드를 사용하여 선언되었다. async는 함수내부에셔 await 키워드를 사용할 수 있게 해준다. await는 프로미스(Promise)가 처리될 때까지 함수 실행을 일시적으로 중지시키고, 프로미스의 결과가 반환되면 함수를 실행한다.
#11: try ~ catch 통신 성공시 try를 실행하고 에러 발생시 catch를 실행한다.
#17: response 에 저장된 값을 text 로 변환한다
<!DOCTYPE html><html lang="ko"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { text-align: center; font-size: 2em; color: white; } .col { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; } </style> </head>
<body> <h1>h1</h1> <div class="col"> <img src="http://qwerew.cafe24.com/images/1.jpg" alt="" /> <img src="http://qwerew.cafe24.com/images/1.jpg" alt="" /> <img src="http://qwerew.cafe24.com/images/1.jpg" alt="" /> <img src="http://qwerew.cafe24.com/images/1.jpg" alt="" /> <img src="http://qwerew.cafe24.com/images/1.jpg" alt="" /> </div> </body></html>