게시판만들기

HTML, CSS, JavaScript + Spring Boot + MyBatis + MySQL 으로 게시판 만들기 (5)

지니★ 2024. 7. 11. 12:42
728x90
728x90
SMALL

HTML, CSS, JavaScript + Spring Boot + MyBatis + MySQL 으로 게시판 만들기 (5)

안녕하세요! 이번 포스트에서는 프론트엔드 디자인을 개선하고 추가 기능을 구현하는 과정을 다뤄보겠습니다.

1. 프론트엔드 디자인 개선

기존의 간단한 디자인을 개선하여 사용자 경험을 향상시키겠습니다. 스타일을 더욱 세련되게 만들고, 사용자 인터페이스를 향상시키기 위해 추가적인 CSS를 작성합니다.

1.1 styles.css 수정

기존의 CSS를 수정하여 더 나은 디자인을 구현합니다.

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
}

.container {
    width: 80%;
    margin: auto;
    overflow: hidden;
}

h1 {
    text-align: center;
    margin-top: 20px;
    color: #333;
}

form {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
    background: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

input[type="text"],
textarea {
    padding: 10px;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 4px;
}

button {
    padding: 10px;
    background-color: #5cb85c;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
}

button:hover {
    background-color: #4cae4c;
}

#posts {
    margin-top: 20px;
}

.post {
    background: white;
    margin-bottom: 20px;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.post h3 {
    margin-top: 0;
}

.post p {
    white-space: pre-wrap;
}

button.edit,
button.delete {
    margin-right: 10px;
}
  

2. 추가 기능 구현

게시글을 수정 및 삭제할 때 확인 메시지를 추가하여 사용자에게 명확한 안내를 제공합니다.

2.1 scripts.js 수정

JavaScript 파일을 수정하여 게시글 수정 및 삭제 시 확인 메시지를 표시합니다.

document.addEventListener("DOMContentLoaded", function() {
    const postForm = document.getElementById("postForm");
    const postsDiv = document.getElementById("posts");

    postForm.addEventListener("submit", function(event) {
        event.preventDefault();

        const title = document.getElementById("title").value;
        const content = document.getElementById("content").value;

        fetch("/api/posts", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ title: title, content: content })
        })
        .then(response => response.json())
        .then(data => {
            fetchPosts();
            alert("게시글이 작성되었습니다.");
        })
        .catch(error => {
            console.error("Error:", error);
            alert("게시글 작성 중 오류가 발생했습니다.");
        });
    });

    function fetchPosts() {
        fetch("/api/posts")
            .then(response => response.json())
            .then(posts => {
                postsDiv.innerHTML = "";
                posts.forEach(post => {
                    const postDiv = document.createElement("div");
                    postDiv.classList.add("post");
                    postDiv.innerHTML = `
                        <h3>${post.title}</h3>
                        <p>${post.content}</p>
                        <button class="edit" onclick="editPost(${post.id}, '${post.title}', '${post.content}')">수정</button>
                        <button class="delete" onclick="deletePost(${post.id})">삭제</button>
                    `;
                    postsDiv.appendChild(postDiv);
                });
            })
            .catch(error => console.error("Error:", error));
    }

    window.editPost = function(id, title, content) {
        if (confirm("이 게시글을 수정하시겠습니까?")) {
            document.getElementById("title").value = title;
            document.getElementById("content").value = content;

            postForm.onsubmit = function(event) {
                event.preventDefault();
                fetch(`/api/posts/${id}`, {
                    method: "PUT",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify({
                        title: document.getElementById("title").value,
                        content: document.getElementById("content").value
                    })
                })
                .then(response => response.json())
                .then(data => {
                    fetchPosts();
                    postForm.reset();
                    postForm.onsubmit = postFormSubmitHandler;
                    alert("게시글이 수정되었습니다.");
                })
                .catch(error => {
                    console.error("Error:", error);
                    alert("게시글 수정 중 오류가 발생했습니다.");
                });
            }
        }
    }

    window.deletePost = function(id) {
        if (confirm("이 게시글을 삭제하시겠습니까?")) {
            fetch(`/api/posts/${id}`, {
                method: "DELETE"
            })
            .then(response => {
                fetchPosts();
                alert("게시글이 삭제되었습니다.");
            })
            .catch(error => {
                console.error("Error:", error);
                alert("게시글 삭제 중 오류가 발생했습니다.");
            });
        }
    }

    const postFormSubmitHandler = postForm.onsubmit;
    fetchPosts();
});
  

3. 마무리

이제 프론트엔드 디자인을 개선하고, 게시글 수정 및 삭제 시 확인 메시지를 추가하여 사용자 경험을 향상시켰습니다. 다음 포스트에서는 추가적인 기능과 최적화를 다뤄보겠습니다. 많은 기대 부탁드립니다!

블로그 포스트에 대한 의견이나 질문이 있으시면 댓글로 남겨주세요!

728x90
728x90
LIST