오전일과
수요일 시험 준비
파일(강사님께서 복습겸 다시 만들어주심 로그인은 제외)
메인 main1.html
로그인 login1.html
회원가입 join1.html
main.css
로그인css는 회원가입이랑 같이쓰기?
join1.css
join1.json
css스타일7 (컨테이너, 헤더, 푸터, 섹션, 네브, 아티클, 네브유엘)
item
상품 글쓰기 만들기 (이미지 첨부 서버 업로드 방법)
유효성 검사
body라는 폼데이터를 만들어서 전송해줌 (이미지 파일이 존재하기 떄문)
(이미지가 없으면) 아래 코드를 이용하여 오브젝트로 전송
const header = {"Content-Type" : "application.json"}
데이터 등록 및 전송 axios.post 이용
복습 자료
main1.html
<!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/main1.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<header> <!-- div사용해도 되는데 알아보기 쉽게 header 아래도 마찬가지 -->
<h3>header</h3>
</header>
<section><!-- 섹션 자체가 가로로 배치하기위한 것을 가지고 있어야함 -->
<nav>
<p>메뉴</p>
<ul>
<li><a href="login1.html">로그인</a></li>
<li><a href="join1.html">회원가입</a></li>
</ul>
</nav>
<article>
<p>내용들</p>
<table>
<!-- 테이블 만들기 -->
</table>
</article>
</section>
<footer>
<h5>footer</h5>
</footer>
</div>
</body>
</html>
main1.css
.container{
width : 100%;
}
header {
background-color: beige;
padding : 20px;
text-align: center;
}
footer {
background-color: rgb(222, 222, 144);
padding : 15px;
text-align: center;
color: black;
}
section {/* section안에는 플렉스로 했다 */
display: flex;
height: 400px;
width : 100%
}
nav {
flex-grow: 2; /* 비율로 주는 것임 nav2:아티클8 */
background-color: aquamarine;
padding : 10px;
}
article {
flex-grow: 8;
background-color: aliceblue;
padding: 10px;
}
nav > ul {
list-style-type: none;
padding-left: 0px;
}
join1.html
<!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/join1.css" rel="stylesheet" />
</head>
<body>
<div class = "container">
<h3>회원가입</h3>
<hr />
<div class="row"><!-- 아이디 -->
<label class="lbl">아이디</label> <!-- label에서 style이 안먹힘(인라인 형식) -->
<input type="text" id="userid" placeholder="아이디" autofocus/>
</div>
<div class="row"><!-- 비밀번호 -->
<label class="lbl">암호</label>
<input type="password" id="userpw" placeholder="암호"/>
</div>
<div class="row"><!-- 비밀번호 확인 -->
<label class="lbl">암호확인</label>
<input type="password" id="userpw1" placeholder="암호확인"/>
</div>
<div class="row"><!-- 이름 -->
<label class="lbl">이름</label>
<input type="text" id="username" placeholder="이름"/>
</div>
<div class="row"><!-- 이메일 -->
<label class="lbl">이메일</label>
<input type="text" placeholder="이메일" id="useremail1"/>
<label>@</label>
<select>
<option>naver.com</option>
<option>gmail.com</option>
<option>daum.com</option>
</select>
</div>
<div style="margin-bottom: 15px;"></div>
<hr />
<div class = "row">
<label class="lbl"></label>
<input type="button" id="btn" value="회원가입" />
</div>
</div>
<script src="js/join1.js"></script>
</body>
</html>
join1.css
.container {
width : 700px;
border : 1px solid #cccccc;
padding : 30px;
margin : 0 auto;
/* 위쪽과 아래쪽이 0일때 auto를 쓰면 가운데 정렬 */
}
/* 질문 앞에 점 왜 붙임? 클래스로 하기때문에 */
.lbl { /* 인라인블락으로 가로 조정 가능하게 함 */
display: inline-block;
width: 100px;
}
.row {
margin-top: 10px;
margin-bottom: 10px;
}
join1.json (스크립트 부분을 따로 작성하여 만든 파일)
join1.html 스크립트부분에 아래 코드 사용
<script src="js/join1.js"></script>
const btn = document.getElementById("btn");
const id = document.getElementById("userid");
const pw = document.getElementById("userpw");
const pw1 = document.getElementById("userpw1");
const name1 = document.getElementById("username");
const email = document.getElementById("useremail1");
btn.addEventListener('click', function(e){
if(id.value === ''){
alert('아이디를 입력하세요.');
id.focus();
return false;
}
if(pw.value === ''){
alert('암호를 입력하세요.');
pw.focus();
return false;
}
if(pw1.value === ''){
alert('암호확인을 입력하세요.')
pw1.focuse();
return false;
}
if(pw.value !== pw1.value){
alert('암호가 일치하지 않습니다.');
pw.focus();
return false;
}
if(name1.value === ''){
alert('이름을 입력해주세요.')
name1.focuse();
return false;
}
if(email.value === ''){
alert('이메일을 입력해주세요.')
email.focuse();
return false;
}
// 벡엔드 연동 되었다고 가정.
alert('회원가입되었습니다.');
window.location.href="main1.html";
});
-item
물픔등록 버튼에 handInsert 첨부
<!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">
물품명 : <input type="text" id="name" /><br/>
가격 : <input type="number" id="price"/><br/>
내용 : <textarea rows="6" id="content"></textarea><br/>
수량 : <input type="number" id="quantity"/><br/>
대표이미지1 : <img src="img/noimage.png" style="width:100px" id="image"/>
<input type="file" onchange="handleImage(this.files)"/><br/>
<input type="button" value="물품등록" onclick="handleInsert()" />
</div>
<script src="./js/axios.min.js"></script>
<script>
// 사용자 입력한 정보를 가져오거나 또는 변경하거나 하래 필요함.
const image = document.getElementById('image');
const name = document.getElementById('name');
const price = document.getElementById('price');
const content = document.getElementById('content');
const quantity = document.getElementById('quantity');
let imagedata = null;
function handleImage(files) {
//{length:숫자}
console.log('handleImage 함수 호출됨.', files);
if(files.length > 0) {
// console.log(URL.createObjectURL(files[0]));
image.src = URL.createObjectURL(files[0]);
//가상의 명령어 크롬 이미지를 보여주기 위해서 가상의 url생성
imagedata = files[0];
}
else{
image.src = './img/noimage.png'
imagedata = null;
}
console.log('handleImage 함수 호출됨', files);
}
function handleInsert(){
//유효성 검사
if(imagedata === null){
alert('이미지 첨부하세요.');
return false;
}
const url = "http://1.234.5.158:23000/item101/insert.json";
// const header = {"Content-Type" : "application.json"}
//오브젝트로 보낼때
const headers = {"Content-Type" : "multipart/form-data"};
//이미지도 있을때는 이렇게 백엔드에 보내줘야함
const body = new FormData();
// const body = {id :'aaa', pw:'bbb'}; //javascript object = json
body.append("name", name.value);
body.append("price", Number(price.value));
body.append("content", content.value);
body.append("quantity", quantity.value);
body.append("image", imagedata);
//호출하는 방법 // 이미지가 있는 것은 post로 무조건
//주소, 전달할 내용, 헤드정보
axios.post(url, body, {headers:headers}).then(function(response) {
// 반환되는 결과를 확인
console.log(response.data);
if(response.data.status === 200){
alert('등록되었습니다.');
window.location.reload();
}
});
}
</script>
</body>
</html>
첨부파일(이미지 선택, 변경, 취소)
function handleImage(files) {
//{length:숫자}
console.log('handleImage 함수 호출됨.', files);
if(files.length > 0) {
// console.log(URL.createObjectURL(files[0]));
image.src = URL.createObjectURL(files[0]);
//가상의 명령어 크롬 이미지를 보여주기 위해서 가상의 url생성
imagedata = files[0];
}
else{
image.src = './img/noimage.png'
imagedata = null;
}
console.log('handleImage 함수 호출됨', files);
유효성 검사(생략)
<input type="button" value="물품등록" onclick="handleInsert()"/>
백엔드로 데이터 넘기기
axios.post(url, body, {headers:headers}).then(function(response) {
// 반환되는 결과를 확인
console.log(response.data);
if(response.data.status === 200){
alert('등록되었습니다.');
window.location.reload();
}
});
오브젝트일때, 이미지가 포함되어있을때
const header = {"Content-Type" : "application.json"}
//오브젝트로 보낼때
const headers = {"Content-Type" : "multipart/form-data"};
//이미지도 있을때는 이렇게 백엔드에 보내줘야함
가져온 데이터를 bodyform에 채워야함.(개체 찾기가 먼저)
const image = document.getElementById('image');
const name = document.getElementById('name');
const price = document.getElementById('price');
const content = document.getElementById('content');
const quantity = document.getElementById('quantity');
const body = new FormData();
body.append("name", name.value);
body.append("price", Number(price.value));
body.append("content", content.value);
body.append("quantity", quantity.value);
body.append("image", imagedata);
위 코드를 보면 Number(price.value)가 있다.
숫자로 확실하게 해주고 넘겨주는 것이 좋다고 함.(price)
어차피 백엔드에서도 하지만 하는게 좋다고 하심.
폼에 데이터 넣을떄 이미지의 경우
펑션으로 변수가 꼬일수도있으니 변수를 외부에 선언
let imagedata = null;
function handleImage(files) {
//{length:숫자}
console.log('handleImage 함수 호출됨.', files);
if(files.length > 0) {
// console.log(URL.createObjectURL(files[0]));
image.src = URL.createObjectURL(files[0]);
//가상의 명령어 크롬 이미지를 보여주기 위해서 가상의 url생성
imagedata = files[0];
}
else{
image.src = './img/noimage.png'
imagedata = null;
}
------ 설명
대표이미지1 : <img src="img/noimage.png" style="width:100px" id="image"/>
<input type="file" onchange="handleImage(this.files)"/><br/>
function handleImage(files) {
//{length:숫자}
console.log('handleImage 함수 호출됨.', files);
if(files.length > 0) {
// console.log(URL.createObjectURL(files[0]));
image.src = URL.createObjectURL(files[0]);
//가상의 명령어 크롬 이미지를 보여주기 위해서 가상의 url생성
imagedata = files[0];
}
else{
image.src = './img/noimage.png'
imagedata = null;
}
console.log('handleImage 함수 호출됨', files);
}
이미지는 오브젝트(object)형식이기 때문에, length를 이용하여 이미지를 첨부했는지 확인
files.length가 0보다 클 경우, 이미지가 존재하는 것이기 때문에
명령어를 이용하여 가상의 크롬 url을 생성하여 이미지를 화면에 표기
그리고 imagedata에 저장
유효성 검사 생략
-itemlist
테이블을 만들어서
아이템 리스트를 만듬.
앞 과정들 + admin.html을 활용하는 시간이 되었음.
<!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>
</head>
<body>
<div class="container">
<table border="1">
<thead>
<tr>
<th>물품번호</th>
<th>물품명</th>
<th>가격</th>
<th>내용</th>
<th>수량</th>
<th>이미지</th>
<th>등록일</th>
<th>버튼</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script src="./js/axios.min.js"></script>
<script>
const tbody = document.getElementsByTagName("tbody");
//tbody 태그 가져오기
console.log(tbody[0]);
//배열이기 때문에 tboby[0]
//[<tbody>] 형태, 여러개라서 getelement"s"
function mount() {
const url = "http://1.234.5.158:23000/item101/selectlist.json"
const headers = {"Content-Type" : "application.json"}
//생략해도 되는데 넣어주는게 좋음 (서버에 따라서 못받을수있음)
axios.get(url, {headers:headers}).then(function(response){
//[{},{},{}---,{}] 99개
console.log(response.data); // 받아온 데이터 콘솔에 출력해보기
for(let tmp of response.data.result){
//리스폰스 데이터에서 리서트 까지 가야함
tbody[0].innerHTML +=
`<tr>` +
`<td>${tmp._id}</td>` +
`<td>${tmp.name}</td>` +
`<td>${tmp.price}</td>` +
`<td>${tmp.content}</td>` +
`<td>${tmp.quantity}</td>` +
`<td><img src="http://1.234.5.158:23000${tmp.img}" style = "width : 50px"></td>`+
`<td>${tmp.regdate}</td>` +
`<td><button onclick="handleDelete(${tmp._id})">삭제</button></td>` +
`</tr>`
}
});
}
mount(); //함수호출
function handleDelete(no){
console.log('handleDelete', no);
const url = `http://1.234.5.158:23000/item101/delete.json?no=${no}`
const headers = {"Content-Type" : "multipart/form-data"};
axios.delete(url, {headers:headers}).then(function(response) {
console.log(response);
if(response.data.status === 200) {
alert('삭제 되었습니다.');
window.location.href='itemlist.html';
}
});
}
</script>
</body>
</html>
function mount() {
const url = "http://1.234.5.158:23000/item101/selectlist.json"
const headers = {"Content-Type" : "application.json"}
//생략해도 되는데 넣어주는게 좋음 (서버에 따라서 못받을수있음)
}
mount();
생략해도 되지만 headers는 넣어주는 것이 좋음. 헤더스
이미지가 url로 올 수도 있음.
해당 서버의 경우 이미지가 url사진으로 옴. (이미지가 url로 오는 것 조심)
function handleDelete(no){
console.log('handleDelete', no);
const url = `http://1.234.5.158:23000/item101/delete.json?no=${no}`
const headers = {"Content-Type" : "multipart/form-data"};
axios.delete(url, {headers:headers}).then(function(response) {
console.log(response);
if(response.data.status === 200) {
alert('삭제 되었습니다.');
window.location.href='itemlist.html';
}
});
}
삭제버튼
-market.html
꽤 어려웠음
박스에 데이터를 집어 넣는 것인데
문제 내주신 box는 일절 사용하지 않고
container[0].innerHTML만 사용하여 박스 여러개를 만듬.
<!DOCTYPE html>
<html lang="ko">
<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>
<style>
.container {
border : 1px solid #cccccc;
width : 800px;
margin : 0 auto;
display : grid;
grid-template-columns : 1fr 1fr 1fr;
grid-auto-rows : minmax(250px, auto);
}
.box {
margin: 5px;
padding: 5px;
border: 1px solid #498d76;
}
a {
text-decoration: none;
color: #111111;
}
a:hover .box{ /* 마우스 커서 올리면 빨갛게 됨 */
border: 1px solid red;
color: red;
}
</style>
</head>
<body>
<div class="container">
<!-- <div class="box">1</div>
<div class="box">1</div>
<div class="box">1</div> -->
</div>
<script src="./js/axios.min.js"></script>
<script>
const container = document.getElementsByClassName("container");
(async function(){ // 자동으로 실행되는 함수
const url = "http://1.234.5.158:23000/item101/selectlist.json";
const headers = {"Content-Type":"application/json"};
const response = await axios.get(url, {headers:headers});
console.log(response.data);
if(response.data.status === 200){
for(let tmp of response.data.result) {
container[0].innerHTML +=
`<a href="marketcontent.html?no=${tmp._id}">`+
`<div class="box">`+
`<p>번호 ${tmp._id}</p>`+
`<img src="http://1.234.5.158:23000${tmp.img}" style="width:100%; height:120px" />`+
`<p>${tmp.name}</p>`+
`<p>${tmp.content}</p>`+
`<p>${tmp.price}원</p>`+
`</div>`+
`</a>`;
}
}
})();
</script>
</body>
</html>
hover , box (호버 박스)를 이용해서 마우스 커서에따라 색이 바뀌는 것을 적용함.
테이블에 넣기만 하던 것보다 훨씬 실용적 가독성 좋음.
-marketcontent.html
너무 어려움.
const url = `http://1.234.5.158:23000/item101/selectlist.json?no=${no}`;
해당 서버에서 정보를 받아오는데item101/selectlist.json?no=${no} 같이 해당 게시물의 정보만 받아와야하는데
배열에서 한번 더 꺼내주어야 하나?
아니라면, 글의 넘버를 찾아서 그 넘버의 정보를 받아야하나?
잘 안됨.
찾아보니까 데이터는 잘 받아오는데 변수를 어떻게 사용해야할지 모르겠음.
axios 개념 GET , POST , DELETE , PUT
해야할 것
main1.html
main1.css
join1.html
join1.css
join1.json
login.html
작성 연습
'html' 카테고리의 다른 글
국비 코딩 풀스택 수업 6일차 (0) | 2022.06.28 |
---|---|
국비 코딩 수강전 준비 (0) | 2022.06.24 |
국비 코딩 풀스택 수업 4일차 (0) | 2022.06.24 |
국비 코딩 풀스택 수업 3일차 (0) | 2022.06.23 |
국비 코딩 풀스택 수업 2일차 (0) | 2022.06.22 |