HTML 간 데이터 전송

이춘구·2022년 1월 7일
6

특정 html 페이지에서 <a> 태그를 클릭했을 때, 링크된 html 페이지로 넘어가며 데이터를 전달하는 두 가지 방법에 대해 설명한다.

URL 이용하기

링크로 이동해서 도착할 페이지(데이터를 받을 페이지) url의 뒤에 데이터를 붙여서 보내는 방법이다.

  • 한글은 url에서 ASCII 코드로 인코딩되므로 전달받는 페이지 쪽에서 decodeURI()로 디코딩 해주어야 한다.
  • 전달하는 데이터가 url에 노출되므로 민감한 정보는 전달하지 않아야 한다.
  • 데이터의 양이 많으면 url이 길어지므로 간단한 데이터만 전달하도록 한다.

보내는 페이지

send.html

<head>
  <script src="send.js" defer></script>
</head>
<body>
  <a href=""/>
</body>

send.js

// 보낼 데이터
const data = 'data';

const aTag = document.querySelector('a');
aTag.addEventListener('click', () => {
  location.href = `receive.html?${data}`;
});

받는 페이지

receive.js

const receivedData = location.href.split('?')[1];
console.log(receivedData); // data

// 전달받은 데이터가 한글일 경우
console.log(decodeURI(receivedData));

localStorage 이용하기

데이터가 url에 노출되면 안 되거나 양이 많을 경우에 사용한다.

  • 민감한 정보의 경우 로컬 스토리지에 저장된 채로 있으면 위험하므로,
    로컬 스토리지에서 꺼내서 변수에 할당한 뒤에는 바로 삭제한다.

보내는 페이지

send.html

<head>
  <script src="send.js" defer></script>
</head>
<body>
  <a href="receive.html"/>
</body>

send.js

// 전달할 데이터
const userInfo = {
  id: "아이디",
  name: "이름",
  password: "비밀번호",
}

const aTag = document.querySelector('a');
aTag.addEventListener('click', () => {
  localStorage.setItem("user-info", JSON.stringify(userInfo));
});

받는 페이지

receive.js

const { id, name, password } = JSON.parse(localStorage.getItem("user-info"));
localStorage.remove("user-info");
console.log(id, name, password); // 아이디 이름 비밀번호
profile
프런트엔드 개발자

1개의 댓글

comment-user-thumbnail
2023년 12월 8일

좋은 글 좋아요~

답글 달기