2/17 TIL

ehllll·2025년 2월 17일

웹개발

JQuery

  • HTML의 요소들을 조작하는 Javascript를 미리 더 쉽게 작성해둔 라이브러리
  • Javascript로 길고 복잡하게 써야하는것을 보다 직관적으로 쓸 수 있음
javascript작성

document.getElementById('hello').innerHTML = '안녕';
jQuery작성

$('#hello').html('안녕');

jJQuery 연습

<!DOCTYPE html>
<html>

<head>
    <title>자바스크립트 문법 연습하기!</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<script>
    function checkResult() {

    }
</script>

<body>
    <div class="top-part">
        <h1>자바스크립트 문법 연습하기!</h1>
    </div>
    <hr />
    <br>
    <h2>1. 함수</h2>
    <div class="button-part">
        <button onclick="checkResult()">결과 확인하기!</button>
    </div>
    <div class="list-part">
        <h2>2. 붙이기</h2>
        <div id="q1">
            <p>사과</p>
            <p></p>
            <p></p>
        </div>
    </div>
    <div class="list-part">
        <h2>3. 붙이기</h2>
        <div id="q2">
            <p>영수는 24살입니다.</p>
            <p>세종은 30살입니다.</p>
            <p>수영은 20살입니다.</p>
        </div>
    </div>
</body>

</html>

이 코드의 checkResult() 함수안에

let fruits = ['사과','배','감','귤','수박']

삽입 후

  • .append()를 활용하여
    ㄴ>
  • 1) 원하는 html 태그를 백틱(````) 으로 묶어주기
  • 2) 태그 안에 들어갈 값은 ${} 로 표시하고, 그 안에는 자료가 있는 변수를 넣어주기
  • 3) 통째로 넣을 html 요소를 $('#아이디')로 골라주시고 append(변수)를 넣어줘서

밑에와 같은 checkResult()함수 만들기

function checkResult() {
	let fruits = ['사과','배','감','귤','수박']
	$('#q1').empty()
	fruits.forEach((a)=>{
		let temp_html = `<p>${a}</p>`
		$('#q1').append(temp_html)
	})
}

fetch

  • 인터넷을 통해 데이터를 요청하고 받아오는 고정
  • 짧은 코드로 데이터를 가져올 수 있음

JQuery+fetch

버튼을 클릭하여 postbox 열고 닫기

  • toggle : 두가지 상태 사이를 전환하는 동작, 어떤 속성이나 상태를 켜거나 끄는 동작
  • head 태그 안에 script 태그 만들기
  • script 태그 안에 function 함수 작성
  • 추억 저장하기 버튼에 onclick 작성
  • div안에 id 선택자 가져오기
  • .toggle() 메서드 작성

완성코드)

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>나만의 추억앨범</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <style>
        @import url('https://fonts.googleapis.com/css2?family=Gowun+Dodum&display=swap');

        * {
            font-family: 'Gowun Dodum', sans-serif;
        }

        .mytitle {
            background-color: green;
            color: white;

            height: 250px;

            /* 내용물을 정렬 */
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            background-image: url('https://images.unsplash.com/photo-1511992243105-2992b3fd0410?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1470&q=80');
            background-position: center;
            background-size: cover;
        }

        .mytitle > button {
            width: 150px;
            height: 50px;
            background-color: transparent;
            border: none;
            color: white;
            font-size: 18px;
            font-weight: bold;
            border-radius: 5px;

            border: 1px solid white;
            margin-top: 20px;
        }

        .mycards {
            margin: 20px auto 20px auto;
            width: 1200px;
        }

        .mypostingbox {
            width: 500px;
            margin: 20px auto 20px auto;
            padding: 20px 20px 20px 20px;
            border-radius: 5px;
            box-shadow: 0px 0px 3px 0px blue;
        }

        .mybtn {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;

            margin-top: 10px;
        }

        .mybtn>button {
            margin-right: 10px;
        }
    </style>
    <script>
        function openclose() {
            $('#postingbox').toggle();
        }
    </script>
</head>

<body>
    <div class="mytitle">
        <h1>나만의 추억 앨범</h1>
        <button onclick="openclose()">추억 저장하기</button>
    </div>
    <div class="mypostingbox" id="postingbox">
        <div class="form-floating mb-3">
            <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
            <label for="floatingInput">앨범 이미지</label>
        </div>

        <div class="form-floating mb-3">
            <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
            <label for="floatingInput">앨범 제목</label>
        </div>

        <div class="form-floating mb-3">
            <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
            <label for="floatingInput">앨범 날짜</label>
        </div>

        <div class="form-floating">
            <textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea"></textarea>
            <label for="floatingTextarea">앨범 내용</label>
        </div>

        <div class="mybtn">
            <button type="button" class="btn btn-dark">기록하기</button>
            <button type="button" class="btn btn-outline-dark">닫기</button>
        </div>
    </div>

    <div class="mycards">
        <div class="row row-cols-1 row-cols-md-4 g-4">
            <div class="col">
                <div class="card h-100">
                    <img src="https://images.unsplash.com/photo-1446768500601-ac47e5ec3719?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1446&q=80"
                        class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">앨범 제목</h5>
                        <p class="card-text">앨범 내용</p>
                    </div>
                    <div class="card-footer">
                        <small class="text-muted">앨범 날짜</small>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card h-100">
                    <img src="https://images.unsplash.com/photo-1446768500601-ac47e5ec3719?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1446&q=80"
                        class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">앨범 제목</h5>
                        <p class="card-text">앨범 내용</p>
                    </div>
                    <div class="card-footer">
                        <small class="text-muted">앨범 날짜</small>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card h-100">
                    <img src="https://images.unsplash.com/photo-1446768500601-ac47e5ec3719?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1446&q=80"
                        class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">앨범 제목</h5>
                        <p class="card-text">앨범 내용</p>
                    </div>
                    <div class="card-footer">
                        <small class="text-muted">앨범 날짜</small>
                    </div>
                </div>
            </div>
            <div class="col">
                <div class="card h-100">
                    <img src="https://images.unsplash.com/photo-1446768500601-ac47e5ec3719?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1446&q=80"
                        class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">앨범 제목</h5>
                        <p class="card-text">앨범 내용</p>
                    </div>
                    <div class="card-footer">
                        <small class="text-muted">앨범 날짜</small>
                    </div>
                </div>
            </div>
        </div>
    </div>


</body>

</html>

클라이언트 - 서버 개념

- JSON은 Key:Value로 이루어져있으며 자료형 Dictionary와 아주 유사함

- GET 요청 이해하기

클라이언트가 요청 할 때, "타입"이 존재
GET : 데이터조회(READ)를 요청시
POST : 데이터생성(CREAT), 변경(UPDATE), 삭제(DELETE) 요청

https://movie.daum.net/moviedb/main?movieId=68593

ㄴ> 이 주소에서 "?"를 기준으로 앞부분이 <서버주소>, 뒷부분이 <영화번호>

GET방식으로 데이터를 전달하는방법

? : 여기서부터 전달할 데이터가 작성된다는 의미
& : 전달할 데이터가 더 있다는 의미

fetch 연습하기

<!doctype html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Fetch 시작하기</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        function hey() {
            alert('연결완료');
        }
    </script>
</head>

<body>
    <button onclick="hey()">fetch 연습!</button>
</body>

</html>

코드해설)

http://spartacodingclub.shop/sparta_api/seoulair

ㄴ> 미세먼지 OpenAPI

fetch("여기에 URL을 입력")
// 이 URL로 웹 통신을 요청한다. 괄호 안에 다른 것이 없다면 GET!
	.then(res => res.json()) 
// 통신 요청을 받은 데이터는 res라는 이름으로 JSON화 한다
	.then(data => { 
		console.log(data) // 개발자 도구에 찍어보기
	}) // JSON 형태로 바뀐 데이터를 data라는 이름으로 붙여 사용한다

ㄴ> Fetch 기본 골격

  • fetch("url입력") <- 이 url로 웹통신요청을 보낸다는뜻
    괄호안에 url만 들어있으면 기본상태인 GET
    .then() <- 통신요청을 받은다음 이렇게 할거라는뜻
    res->res.json()
    ㄴ> 통신요청을 받은 데이터는 res라는 이름을 붙일거라는뜻(변경가능)
    ㄴ> res는 JSON형태로 바꿔서 조작할수있게 한다는뜻
    .then(data->{})
    ㄴ> JSON형태로 바뀐 데이터를 data라는 이름으로 붙일거라는뜻
  • GET요청은 , url뒤에 아래와 같이 붙여서 데이터를 가져감
http://naver.com?param=value&param2=value2 
  • POST요청은, data:{}에 넣어서 데이터를 가져감
data: { param: 'value', param2: 'value2' },
  • success : 성공하면, response값에 서버의 결과값을 담아서 함수를 실행함

완성코드)

<!doctype html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Fetch 시작하기</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        function hey() {
            let url = 'http://spartacodingclub.shop/sparta_api/seoulair';
            fetch(url).then(res => res.json()).then(data => {
                console.log(data['RealtimeCityAir']['row'][0])
            })
        }
    </script>
</head>

<body>
    <button onclick="hey()">fetch 연습!</button>
</body>

</html>

0개의 댓글