SweetAlert2를 활용해 사용자 입력값을 받고, 이를 Fetch API로 서버에 전송하는 실전 예제를 소개합니다. 간단한 코드만으로 알림창, 입력폼, 비동기 요청까지 구현할 수 있어 웹 프로젝트에 유용하게 활용됩니다.
SweetAlert2 + Fetch API 연동 예제
<!-- SweetAlert2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
HTML// 버튼 클릭 시 실행
document.getElementById('send-btn').addEventListener('click', () => {
Swal.fire({
title: '이메일을 입력해주세요',
input: 'email',
inputPlaceholder: 'example@email.com',
showCancelButton: true,
confirmButtonText: '전송',
cancelButtonText: '취소',
preConfirm: (email) => {
if (!email) {
Swal.showValidationMessage('이메일을 입력해주세요');
return false;
}
// fetch API 호출
return fetch('/submit-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email })
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.catch(error => {
Swal.showValidationMessage(`요청 실패: ${error}`);
});
}
}).then((result) => {
if (result.isConfirmed && result.value) {
Swal.fire('완료!', '이메일이 성공적으로 전송되었습니다.', 'success');
}
});
});
JavaScript- preConfirm : 사용자 입력 후 서버 요청을 넣을 때 사용
- Swal.showValidationMessage() : 검증 실패 시 메시지 표시
- fetch() : 입력값을 JSON 형태로 POST 요청
예제 실행
- 이 페이지 예제 실행은 오류가 발생하는게 정상입니다. /submit-email 백엔드 처리 파일이 없습니다.
- SweetAlert2 사용해서 백엔드 서버 요청 예제로 간단하게 활용이 가능합니다.
- SweetAlert2 사용법은 이제 어느정도 익숙해진거 같습니다. 핵심은 fetch API 호출 이 부분입니다.