html

국비 코딩 풀스택 수업 4일차

비루블 2022. 6. 24. 21:16

 


오전일과

(board, boardone)

 

board

글번호, 제목 누르면 사이트 이동하는 것 복습

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>게시판</title>
    <link href="./css/bootstrap.min.css" rel="stylesheet" />

</head>
<body>
    <div class="container" style="margin-top: 20px; border:1px solid #cccccc">
        <div style="margin-top: 20px;">
            <h3>게시판</h3>
            <hr />
        </div>

        <a href="boardwrite.html" class="btn btn-success">글쓰기</a>
        <!--아래는 bootrap에서 class를 땡겨온 것임-->
        <!--페이지 이동 태그는 a태그(href)-->

        <table class="table table-hover">
        <!--부트스트랩에서 테이블에 양식클래스를 끌어옴-->
        <!--목록을 보여줄때는 테이블을 많이 쓴다.-->
            <thead>
            <!--헤드는 행-->
                <tr>
                    <th>글번호</th>
                    <th>제목</th>
                    <th>작성자</th>
                    <th>조회수</th>
                    <th>날짜</th>
                </tr>
            </thead>
            <tbody id = "tbody">
            </tbody>

        </table>
    </div>
    
    <script>
        const xhr = new XMLHttpRequest();
        const ur1= "http://1.234.5.158:23000/board/selectlist.json?page=1";
        xhr.open('GET', ur1);
        xhr.send(); 

        xhr.addEventListener('load', function(e){
            const response = JSON.parse(xhr.response);
            const tbody = document.getElementById('tbody');
            console.log(response); // [{…}, {…}]

            if(response.status === 200){
                for(let tmp of response.result){
                    tbody.innerHTML +=
                    `<tr>`+
                        `<td><a href="boardone.html?no=${tmp.no}">${tmp.no}</a></td>` +
                        `<td><a href="boardone.html?no=${tmp.no}">${tmp.title}</a></td>` +
                        //위에는 제목을 누르면 a태그로 이동하게끔함
                        //?no=${tmp.no}">${tmp.title}를 붙이면 어디 페이지에서 이동해왔는지 말게됨
                        //a태그 위에는 전달하고자하는 정보
                        `<td>${tmp.writer}</td>` +
                        `<td>${tmp.hit}</td>` +
                        `<td>${tmp.regdate}</td>` +
                    `<tr>`;
                }
            }
            else{
                alert('서버오류')
            }

            
        });



    </script>
</body>
</html>

서버에서 정보를 받아온뒤

테이블에 기입하고

no 와 title 을 클릭시 해당 게시물 페이지(boardone.html)로 이동하게끔 만듬

 


boardone

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="./css/style1.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <h3>게시판 내용</h3>
        <hr />

        <p id="no">여기는 글번호 </p>
        <p id="title">여기는 제목 </p>
        <p id="content">여기는 내용 </p>
        <p id="writer">여기는 작성자 </p>
        <p id="hit">여기는 조회수 </p>
        <p id="regdate">여기는 날짜 </p>

        <button onclick="handleDelete()">삭제</button>
        <button onclick="handleUpdate()">수정</button>
    </div>

    <script src="./js/axios.min.js"></script>
    <script>
        // 127.0.0.1:5500/boardone.html?no=207  =>  207 가져오기
        const href = new URL(window.location);
        const urlParam = href.searchParams;
        const no = urlParam.get("no");
        console.log(no);


        if(no === null) {  // no가 없을 경우 강제로 목록으로 이동시킴
            window.location.href="board.html";
        }

        // 벡엔드에서 내용을 받아서 p태그에 표시하기
        const url = `http://1.234.5.158:23000/board/selectone.json?no=${no}`;
        
        axios.get(url).then(function(response){
            console.log(response);
            console.log(response.data.result);
            const obj = response.data.result;

            const no = document.getElementById("no");
            no.innerHTML = obj.no;

            const title = document.getElementById("title");
            title.innerHTML = obj.title;
            
            const content = document.getElementById("content");
            content.innerHTML = obj.content;
            
            const writer = document.getElementById("writer");
            writer.innerHTML = obj.writer;
            
            const hit = document.getElementById("hit");
            hit.innerHTML = obj.hit;

            const regdate = document.getElementById("regdate");
            regdate.innerHTML = obj.regdate;
        });

        function handleDelete() { // 호출되기 전까지 수행되지 않음
            const url =`http://1.234.5.158:23000/board/delete.json?no=${no}`;

            //벡엔드로 호출하고 결과값을 response로 받음
            axios.delete(url).then(function(response) {
                console.log(response);
                if(response.data.status === 200) {
                    alert('삭제 되었습니다.');
                    window.location.href='board.html';
                }
            });
        }


        function handleUpdate() { // 호출되기 전까지 수행되지 않음
            
            // javascript로 url주소를 변경후에 엔터키를 누름
            window.location.href=`boardupdate.html?no=${no}`;

        }
       
    </script>
</body>
</html>

버튼 기입

        <button onclick="handleDelete()">삭제</button>
        <button onclick="handleUpdate()">수정</button>

function handleDelete()

function handleUpdate()

활용하여 수정 버튼과 삭제버튼에 의미를 부여

 

if(no === null) { 
            window.location.href="board.html";

no가 없을 경우 강제로 목록으로 이동시킴

게시물을 누르지않고 바로 이동하려고 하는 것을 차단

 

게시물 화면
온마운트, 마운트한다(화면이 로딩되는 것을 준비한다)
컴퓨터에서 Mount란 어떠한 것을 Available 한 상태로 준비하는 것을 말한다.
좀 더 추상적인 개념이지, 딱 하나로 이어지는 구체적인 단어는 아니다.

아래는 온마운트 코드

        // 127.0.0.1:5500/boardone.html?no=207  =>  207 가져오기
        const href = new URL(window.location);
        const urlParam = href.searchParams;
        const no = urlParam.get("no");
        console.log(no);

        
        if(no === null) {  // no가 없을 경우 강제로 목록으로 이동시킴
            window.location.href="board.html";
        }

        // 벡엔드에서 내용을 받아서 p태그에 표시하기
        const url = `http://1.234.5.158:23000/board/selectone.json?no=${no}`;
        
        axios.get(url).then(function(response){
            console.log(response);
            console.log(response.data.result);
            const obj = response.data.result;

            const no = document.getElementById("no");
            no.innerHTML = obj.no;

            const title = document.getElementById("title");
            title.innerHTML = obj.title;
            
            const content = document.getElementById("content");
            content.innerHTML = obj.content;
            
            const writer = document.getElementById("writer");
            writer.innerHTML = obj.writer;
            
            const hit = document.getElementById("hit");
            hit.innerHTML = obj.hit;

            const regdate = document.getElementById("regdate");
            regdate.innerHTML = obj.regdate;
        });

 

 

 

boardone_me 파일과 boardone 파일 비교

계속 나만 에러 떳음. 

이유 :

1. 버튼 두개 안만들음

// 127.0.0.1:5500/boardone.html?no=207  =>  207 가져오기
const href = new URL(window.location);
        const urlParam = href.searchParams;
        const no = urlParam.get("no");

2. 서버로부터 정보를 받아오는 코드를 기입안함.


오후일과

admin

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>관리자페이지</title>
</head>

<body>
    <div class="container">
        <a href="admin.html?menu=1"><button>게시물관리</button></a>
        <a href="admin.html?menu=2"><button>회원관리</button></a>
        <a href="admin.html?menu=3"><button>물품관리</button></a>
        <a href="admin.html?menu=4"><button>주문관리</button></a>
        <hr />

        <div id="menu1" class="menu">
            <h3>게시물관리</h3>
            <table border="1">
                <thead>
                    <th>번호</th>
                    <th>제목</th>
                    <th>작성자</th>
                    <th>조회수</th>
                    <th>등록일</th>
                    <th>버튼</th>
                </thead>
                <tbody id="tbody1">
                </tbody>
            </table>
        </div>

        <div id="menu2" class="menu">
            <h3>회원관리</h3>
        </div>

        <div id="menu3" class="menu">
            <h3>물품관리</h3>
        </div>

        <div id="menu4" class="menu">
            <h3>주문관리</h3>
        </div>
    </div>

    <script src="./js/axios.min.js"></script>
    <script>
        console.log(window);
        const href = new URL(window.location);
        const urlParam = href.searchParams;
        const menu = urlParam.get("menu");
        console.log(typeof menu, menu);//타입과 값 확인

        // menu  = 3
        // [ <div>, <div>, <div>, <div> ]
        
        // 4개의 항목을 가져옴    
        const menus = document.getElementsByClassName("menu");
        
        // 가져온 항목의 개수
        console.log(menus.length); // 4

        // 0 부터 개수만큼 반복 ex) 0 1 2 3
        for(let i=0; i<menus.length; i++) {
            console.log(i);
            menus[i].style.display = "none";
        }

        // menu값에서 1을 뺀 위치는 표시
        const idx = Number(menu) - 1; 
        menus[idx].style.display = "";

        if(menu === '1'){ //게시물관리
            const url = `http://1.234.5.158:23000/board/selectlist.json`;
            axios.get(url).then(function(response){
                // [{},{},{} ... {}]
                console.log(response.data.result);
                const tbody1 = document.getElementById('tbody1');

                for(let tmp of response.data.result) {
                    tbody1.innerHTML += 
                        `<tr>` +
                            `<td>${tmp.no}</td>` +
                            `<td>${tmp.title}</td>` +
                            `<td>${tmp.writer}</td>` +
                            `<td>${tmp.hit}</td>` +
                            `<td>${tmp.regdate}</td>` +
                            `<td>` +
                                `<button onclick="handleDelete(${tmp.no})">삭제</button>` + 
                                `<button onclick="handleUpdate(${tmp.no})">수정</button>` + 
                            `</td>` +
                        `</tr>`;
                }
            });
        }

        // 삭제 버튼을 눌렀을 때
        function handleDelete(no){
            const url = `http://1.234.5.158:23000/board/delete.json?no=${no}`
            axios.delete(url).then(function(response) {
                console.log(response);
                if(response.data.status === 200) {
                    alert('삭제 되었습니다.');
                    // 백엔드의 삭제를 호출하고 성공 시
                    window.location.href = "admin.html?menu=1";                }
            });
            
        }


        function handleUpdate(no){
            window.location.href=`boardupdate.html?no=${no}`;


        }

    </script>
</body>
</html>

관리자 홈페이지를 따로 제작

게시물관리, 회원관리, 물품관리, 주문관리

버튼을 만들어서, 페이지는 그대로 있는데

아래 내용만 바뀌도록 만들었음.

이때 메뉴를 각각 누를때 마다 나오는 것을 class화 시켜서 for문으로 숨겨줬음.

(본질은 모두 표기이고, 해당 버튼을 누르면, 전부 none으로 표기이후, 선택한 메뉴를 표기) 아래 참고

        // 0 부터 개수만큼 반복 ex) 0 1 2 3
        for(let i=0; i<menus.length; i++) {
            console.log(i);
            menus[i].style.display = "none";
        }

        // menu값에서 1을 뺀 위치는 표시
        const idx = Number(menu) - 1; 
        menus[idx].style.display = "";

let으로 변수 선언, menus의 길이만큼 반복, i++

0,1,2,3을 none으로 표기하여라(menus[i]는 div에 있는 게시물관리, 회원관리, 물품관리, 주문관리)

menu는 1부터 시작하기때문에 -1을 붙여줌

 


후기

아침 일찍 일어났다가 다시 잠들어 버려서 첫지각을 함.

다행히 많이 안늦어서 수업을 따라갈 수 있었음.

admin 작업을 할때  ``(템퍼릿리터럴)을 이상하게 적어서 나혼자만 화면에 표 안나올때 상당히 당황했음.

옆에분들하고 확인했을때도 분명 코드는 맞았는데...

결국 강사님한테 스크립트 요청해서 해결하였다.

스크립트 비교 결과 템퍼릿을 잘못표기 ㅜㅜ;

 

사이트 추천(강사님이랑 코드 비교하면서 다시 고쳐쓸때, 어디가 틀렸는지 알아내기 유용함.)

https://www.diffchecker.com/

 

Diffchecker

Try our desktop app Offline diffing, advanced features and more

www.diffchecker.com

 

'html' 카테고리의 다른 글

국비 코딩 풀스택 수업 5일차  (0) 2022.06.27
국비 코딩 수강전 준비  (0) 2022.06.24
국비 코딩 풀스택 수업 3일차  (0) 2022.06.23
국비 코딩 풀스택 수업 2일차  (0) 2022.06.22
국비 코딩 풀스택 수업 1일차  (0) 2022.06.21