🐨CoalaCoding
DocsExamplesTry itBoardB반B반
🐨CoalaCoding

개발자를 위한 한국어 웹 기술 문서

문서

  • JavaScript
  • Web Publishing
  • React
  • Python

커뮤니티

  • 게시판
  • 예제 모음
  • Try it 에디터

기타

  • GitHub
  • 관리자
© 2026 CoalaCoding. All rights reserved.
  • topBtn
  • rollingBanner
  • menu
  • stickyMenu
  • accordion
  • swiper
  • activeMenu
  • slide
  • tab
  • scrollEffect
  • ajax
  • tabSlide
  • adaption
  • 좋은-디자인을-위한-요소
  • 논리적vs물리적해상도
  • 게슈탈트이론
  • 색채심리학
  • 황금비율
  • 컬러모드
  • 디자인실무용어
  • 이미지파일의특징
  • 폰트와사이즈
  • 레이아웃기초
  • 10가지법칙
  • 아이트래킹
  • 색상을성공적으로고르는방법
  • 타이포그래피10가지팁
  • 스타일가이드만들기
  • 모바일디자인버튼
  • 조형요소
  • 6가지비주얼체계규칙
  • 아이콘디자인이론
  • 해상도와그리드시스템
  • 피그마란
  • 작업환경세팅
  • 인터페이스예제
  • 기능심화
  • 인터페이스설계
  1. 홈
  2. 문서
  3. HTML & CSS
  4. UI 컴포넌트
  5. ajax

ajax

코드 블록의 Try it Yourself 버튼으로 직접 실행할 수 있다.

구문

jQuery load()는 특정 URL의 리소스를 요청하고, 응답을 HTML로 변환하여 지정된 DOM 요소에 로드합니다.

💡 ajax (Asynchronous JavaScript and XML) (에이싱크러너스 자바스크립트 앤 xml) 비동기 방식의 자바스크립트와 xml

  • 동기방식: 서버에 신호를 보냈을때 응답이 돌아와야 다음 동작을 수행
  • 비동기방식: 신호를 보냈을때 응답여부와 상관없이 다음 동작 실행

💡Ajax(Asynchronous Javascript and XML)는 클라이언트 가 비동기방식으로 자바스크립트를 이용하여 > 화면 전환 없이 서버측에 자료(XML,HTML,JSON,텍스트...)를 요청할때 사용

예제

미리보기

미리보기

HTML

<!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>

CSS

.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;
}

JQ

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');
});

Vanilla

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 로 변환한다

SUB

<!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>

목차

  • 구문