
SweetAlert
- 기존의 브라우저 기본 alert() 창을 예쁘고 현대적인 모달 팝업으로 바꿔주는 라이브러리
- 확인/취소 버튼, 아이콘, 애니메이션, 커스터마이징 등이 가능
- 웹사이트에서 경고창·성공창·확인창 등을 만들 때 가장 많이 쓰이는 도구 중 하나
특징
- 디자인이 매우 깔끔하고 현대적
- 버튼 2개 이상 가능
- 확인 / 취소
- 네 / 아니오
- Yes / No / Cancel
- 아이콘 제공
- success (성공) error (에러) warning (경고) info (정보) question (질문)
- 비동기 처리/콜백에 강함
- 사용자가 “확인”을 누를 때만 특정 동작을 수행하도록 만들 수 있음
사용법
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
- CDN 1줄만 추가하면 바로 사용 가능함
- 보통 base.html에 넣는 것이 정석 (base.html 안에서
</body> 바로 위₩)
- base.html에 SweetAlert2를 넣으면 모든 하위 템플릿에서 즉시 Swal 사용 가능해짐
코드 패턴(예시)
1. 기본 알림 (Success / Error / Info / Warning)
Swal.fire("완료!", "작업이 성공적으로 처리되었습니다.", "success");
Swal.fire("오류!", "문제가 발생했습니다.", "error");
Swal.fire("주의!", "확인이 필요합니다.", "warning");
Swal.fire("정보", "이것은 정보 메시지입니다.", "info");
Swal.fire({
title: "정말 삭제하시겠습니까?",
text: "삭제된 파일은 복구할 수 없습니다.",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#d33",
cancelButtonColor: "#6c757d",
confirmButtonText: "삭제",
cancelButtonText: "취소"
}).then((result) => {
if (result.isConfirmed) {
}
});
const Toast = Swal.mixin({
toast: true,
position: "top-end",
showConfirmButton: false,
timer: 2000,
timerProgressBar: true
});
Toast.fire({
icon: "success",
title: "업로드 완료!"
});
4. 텍스트 입력 받기 (비밀번호 확인, 이름 입력 등)
Swal.fire({
title: "이름을 입력하세요",
input: "text",
inputPlaceholder: "예: 김기훈"
}).then(result => {
console.log(result.value);
});
5. 로딩 스피너 표시
- 파일 업로드/분석 실행/서버 작업 대기 등에 사용
Swal.fire({
title: "처리 중...",
text: "잠시만 기다려주세요.",
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
}
});
Swal.fire({
title: "완료!",
text: "작업이 성공적으로 완료되었습니다.",
icon: "success",
timer: 1500,
showConfirmButton: false
}).then(() => {
window.location.href = "/files/list/";
});
Swal.fire({
title: "<strong>공지사항</strong>",
html: `
<p>이 메시지는 <b>HTML</b>을 포함할 수 있습니다.</p>
<a href="/help">도움말 보기</a>
`,
icon: "info"
});
8. Ajax 요청 + SweetAlert 조합
Swal.fire({
title: "정말 삭제하시겠습니까?",
icon: "warning",
showCancelButton: true
}).then((result) => {
if (result.isConfirmed) {
fetch("/api/delete/1/", { method: "DELETE" })
.then(() => {
Swal.fire("삭제 완료!", "", "success");
});
}
});