일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- Java
- git amend
- PathVariable
- assertequals
- BCryptPasswordEncoder
- SQL
- 부적합한열
- git
- WHEREIN
- MVC
- oracle
- passwordencoder
- JavaScript
- ResultType
- springboot
- Spring
- localStorage
- 배열
- mybatis
- react
- Thymeleaf
- JDBC
- Variabla
- git reset
- 이딴게개발자
- useContext
- content-box
- git revase
- HTML
- CRUD
- Today
- Total
개발새발
[JavaScript] localStorage를 이용한 게시글 추가 본문
1. 어떤 프로그램을 만들 것인가?
외부 페이지에서 작성한 글이메인 페이지에 업로드 되는 프로그램
2. 어떻게 구현할 것인가?
- 메인페이지에서 글쓰기 버튼을 누르면 글을 작성하는 페이지로 이동한다
- 이동한 페이지에서 원하는 글을 쓰고, 작성완료 버튼을 누르면
① localStorage에 작성한 글이 저장되고
② 저장된 정보가 메인페이지에 업로드 된다
③ 그리고 메인페이지로 자동 이동
코드를 작성해보자!
일단 페이지 구조를 먼저 짜봅시다
1. 게시판 페이지 (post-main.html)
참고로 css코드는 따로 파일을 만들어서 적용했습니다
<!DOCTYPE html>
<html>
<head>
<title>블로그 메인</title>
</head>
<body>
<h1>게시판</h1>
<button id="createPostButton">글쓰기</button>
<ul id="postList"><!--작성한 글 리스트 올라오는 곳--></ul>
</body>
</html>
2. 게시글 작성 페이지 (create-post.html)
<!DOCTYPE html>
<html>
<head>
<title>게시글 작성</title>
</head>
<body>
<h1>게시글 작성</h1>
<textarea id="blogPost" placeholder="게시글을 작성하세요"></textarea>
<button id="saveButton">작성완료</button>
</body>
</html>
~~~여기서부터는 JavaScript~~~
post-main.html : 글쓰기 버튼 누르면 페이지 이동
document.getElementById("createPostButton").addEventListener("click",function(){
window.location.href = "create-post.html"; //location.href : 동일한 디렉토리 내 파일을 선택
});
create-post : 작성완료 버튼 누르면 textarea에서 작성한 글을 localStorage에 저장
document.getElementById("saveButton").addEventListener("click", function() {
//textarea에 작성한 값을 postContent 변수에 할당
const postContent = document.getElementById("blogPost").value;
//postContent가 공백이 아닐 경우
if (postContent.trim() !== "") {
const timestamp = new Date().getTime();
const blogPost = {
id: timestamp,
content: postContent, //blogPost의 content는 postContent 그 자체
};
//savedPosts : 작성된 글을 저장할 배열 생성
const savedPosts = [];
//작성된 글(blogPost) 배열에 추가
savedPosts.push(blogPost);
//key값이 blogPosts인 localStorage에 savedPostsf를 문자열로 변환해서 저장
localStorage.setItem("blogPosts", JSON.stringify(savedPosts));
alert("게시글이 저장되었습니다.");
// 블로그 메인 페이지로 이동
window.location.href = "post-main.html";
} else {
//postContent가 공백일 경우 보이는 메세지(작성된 글이 없을 때)
alert("게시글 내용을 입력하세요.");
}
});
post-main.html : localStorage에 저장된 값 불러오는 코드 추가
const postList = document.getElementById("postList");
//저장된 데이터가 없을 시 빈 배열[]을 기본값으로 사용
const savedPosts = JSON.parse(localStorage.getItem("blogPosts")) || [];
savedPosts.forEach(post => {
const listItem = document.createElement("li"); //저장된 각 데이터를 li에 넣기
listItem.textContent = post.content;
postList.appendChild(listItem); //ul에 데이터가 담긴 li 추가
});
와~ 이제 작동이 되는지 테스트를 해보자
그럼 이제 여기서 끝인가?
노우.. 문제가 생겼다
이게 무슨 일인가..
분명 localStorage는 데이터 삭제를 명시하지 않는한 영구하게 지속되는 저장소로 알고있었는데?
문제는 create-post에서 작성한 JavaScript 코드에 있었다
처음에는 이게 왜 안되지?했는데 생각해보니까 당연한 것이었다
작성 완료 버튼을 누를 때마다 savedPosts라는 빈 배열만 localStorage에 갖다 바치고 있었으니
뭐가 쌓일래야 쌓일 수가 없었던 것...
그럼 어떻게 고쳐야 되는가?
blogPosts를 key값으로 가지는 localStorage에 있는 아이템을 가지고 와서
거기에 계속 추가한다고 수정하면 된다
|| [ ] ☜ 얘는 진짜 처음 글을 작성할 때를 위해 있는 놈
~~~최종 코드~~~
<post-main.html>
<!DOCTYPE html>
<html>
<head>
<title>블로그 메인</title>
<link rel="stylesheet" type="text/css" href="../css/post-main.css">
</head>
<body>
<h1>게시판</h1>
<button id="createPostButton">글쓰기</button>
<ul id="postList"><!--작성한 글 리스트 올라오는 곳--></ul>
<script>
document.getElementById("createPostButton").addEventListener("click",function(){
window.location.href = "create-post.html"; //location.href : 동일한 디렉토리 내 파일을 선택할 때
});
const postList = document.getElementById("postList"); //<ul>태그
const savedPosts = JSON.parse(localStorage.getItem("blogPosts")) || [];
savedPosts.forEach(post => {
const listItem = document.createElement("li");
listItem.textContent = post.content;
postList.appendChild(listItem);
});
</script>
</body>
</html>
<create-post.html>
<!DOCTYPE html>
<html>
<head>
<title>블로그 게시글 작성</title>
<link rel="stylesheet" type="text/css" href="../css/create-post.css">
</head>
<body>
<h1>게시글 작성</h1>
<textarea id="blogPost" placeholder="게시글을 작성하세요"></textarea>
<button id="saveButton">작성완료</button>
<script>
document.getElementById("saveButton").addEventListener("click", function() {
const postContent = document.getElementById("blogPost").value;
if (postContent.trim() !== "") {
const timestamp = new Date().getTime();
const blogPost = {
id: timestamp,
content: postContent,
};
const savedPosts = JSON.parse(localStorage.getItem("blogPosts")) || [] ;
savedPosts.push(blogPost);
localStorage.setItem("blogPosts", JSON.stringify(savedPosts));
alert("게시글이 저장되었습니다.");
// 블로그 메인 페이지로 이동
window.location.href = "post-main.html";
} else {
alert("게시글 내용을 입력하세요.");
}
});
</script>
</body>
</html>
게시글 추가 공간은 굳이 ul, li사용 할 필요 없이
태그는 본인 맘대로 지정해도 문제없다
그럼 진짜 끝!!!
'FRONT > HTML_CSS_JS' 카테고리의 다른 글
[JavaScript] localStorage를 이용한 사진 업로드. 근데 이제 팝업창을 곁들인 (2) | 2023.11.04 |
---|---|
[CSS] box-sizing: border-box (1) | 2023.10.30 |