본문 바로가기

HTML, CSS, Javascript

[Javascript] HTML form 새로고침 없이 데이터 보내는 법

개요

간단한 로그인 기능을 구현할 때 form 태그를 사용하면 버튼 클릭 시 페이지가 새로고침되는 문제가 발생할 수 있다. 이로 인해 입력한 값이 사라지거나 원하는 동작이 실행되지 않을 수 있습니다. form 태그가 새로고침을 유발하는 이유와 이를 막는 방법에 대해 알아보자.

 

 


 

 

목차

  1. form 태그
  2. 새로고침 발생하는 이유
  3. 새로고침 막는 방법

 

 


 

 

form 태그

form 태그는 HTML에서 사용자 입력을 서버로 전송하기 위한 영역을 정의하는 태그이다. 주로 로그인, 회원가입, 검색 등의 입력 데이터를 다룰 때 사용된다.

 

 

form 사용 예

<form>
  <input type="text" name="username" />
  <input type="password" name="password" />
  <button type="submit">로그인</button>
</form>

 

 

 


 

 

새로 고침이 발생하는 이유

 

form 태그에서 <button type="submit"> 혹은 <input type="submit"> 요소를 클릭하면, 브라우저는 기본적으로 폼 데이터를 action에 지정된 경로로 전송하고 페이지를 새로고침하거나 이동합니다. 이 기본 동작이 바로 우리가 흔히 겪는 새로고침의 원인입니다.

<form action="/login" method="POST">
  <input type="text" name="username" />
  <input type="password" name="password" />
  <button type="submit">로그인</button>
</form>
  • button은 form 태그 내에서 기본적으로 type="submit"이다. 

 

 


 

 

새로고침 막는 방법

2가지 방법이 있다. button type을 바꾸는 방법자바스크립트로 막는 방법이 있다.

 

 

button type을 바꾸는 방법

<form id="loginForm">
  <input type="text" name="username" />
  <input type="password" name="password" />
  <button type="button">로그인</button>
</form>

 

 

자바스크립트로 막는 방법

브라우저는 어떤 이벤트가 발생했을 때, 기본적으로 정해진 동작을 실행한다.

 

예를 들어 :

 

  • <form>의 submit → 페이지 새로고침
  • <a href="#"> 클릭 → 페이지 상단으로 이동
  • <button type="submit"> → 폼 제출

event.preventDefault()를 사용하면 이 기본 동작을 막을 수 있다.

 

<form id="loginForm">
  <input type="text" name="username" />
  <input type="password" name="password" />
  <button type="submit">로그인</button>
</form>

<script>
  const form = document.getElementById("loginForm");

  form.addEventListener("submit", function (event) {
    event.preventDefault();
    const username = form.username.value;
    const password = form.password.value;
    console.log("입력된 아이디:", username);
    console.log("입력된 비밀번호:", password);
  });
</script>

input에서 name을 적용하면, form 요소의 DOM 객체에서 해당 name으로 직접 접근이 가능하다.

  • const username = form.username.value;가 그 예이다.