스파르타 웹종 2주차

looggi·2022년 7월 10일
1

java script 복습

<head>
  <script>
   let count=0
   
   function hey(){
   count+=1
   
   if(count%2==0){
   alert('짝수입니다')
   }else{alert('홀수입니다')
   }
   
   }
   
  </script>
</head>

또는

<head>
  <script>
   let count=1
   
   function hey(){
   
   if(count%2==0){
   alert('짝수입니다')
   }else{alert('홀수입니다')
   }
   count+=1 
   
   }
   
  </script>
</head>

JQuery

  • HTML의 요소들을 조작하는, 편리한 Javascript를 미리 작성해둔 것. 라이브러리!
    👉 Javascript로도 모든 기능(예 - 버튼 글씨 바꾸기 등)을 구현할 수는 있지만,
    1) 코드가 복잡하고, 2) 브라우저 간 호환성 문제도 고려해야해서, JQuery라는 라이브러리가 등장하게 되었답니다.
    👉jQuery는 Javascript와 다른 특별한 소프트웨어가 아니라 미리 작성된 Javascript 코드입니다. 전문 개발자들이 짜둔 코드를 잘 가져와서 사용하는 것임을 기억해주세요! (그렇게 때문에, 쓰기 전에 "임포트"를 해야합니다!)
    👉<head>~</head>사이에 추가해주면 됨
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
 </script>

(링크:https://www.w3schools.com/jquery/jquery_get_started.asp)

input box 값을 가져오기/넣기

일단 가르킬 수 있어야한다!
css에서는 class/ javascript에서는 id(아래에선 url)

<div class="form-floating mb-3">
    <input id="url" type="email" class="form-control" placeholder="name@example.com">
    <label>영화URL</label>
</div>
  • $('#url').val(); 👉'#id' 인 곳에 $() jquery를 .val()을 먹이겠다.

  • $('#url').val('넣고 싶은 값');

box(div)감추기/ 보여주기

  • $(#'post-box').hide();

  • $(#'post-box').show();

태그 붙이기

<div class="cards"...>
   <div class="card"...>
   <div class="card"...>
   <div class="card"...>
</div>       
    

아래에 연속해서 카드를 붙이고 싶다면,

<div id='card-box' class="cards"...>
   <div class="card"...>
   <div class="card"...>
   <div class="card"...>
</div>       
    

카드들이 모여있는 div에 id를 주고, 그곳에 연속해서 카드들을 붙이겠다 👉
let temp_html=<button>나는 버튼이다</button>
지금 백틱 안의 문구는 html 형식이긴 하지만 그냥 문자열이다. 하지만 이걸 jquery를 이용해 html화 할 수 있다.
$(#'card-box').append(temp_html)
id가 가르키는 곳에 괄호안의 temp_html을 html화해서(지금은 문자열이 버튼을 만드는 문장이라 버튼으로 만들어짐) 붙이겠다

카드를 연속해서 붙이고 싶다면 temp_html=`` 속에 카드 코드를 가져와서 붙이면 그 코드를 html화해서 붙여준다

모든 제목은 다르게 들어가야하므로...

let temp_html=``코드 속에 각각의 영화 제목이 들어가야 하는 부분에 jquery를 써주면 된다. mytitle이 리스트화 돼서 업데이트되면 그걸 받아와서 새로운 박스에는 새로운 제목이, 모든 박스에 모두 다른 제목이 들어갈 수 있다.

<div class="mycards">
    <div class="row row-cols-1 row-cols-md-4 g-4" id="cards-box">
        <div class="col">
            <div class="card h-100">
                <img src="https://movie-phinf.pstatic.net/20210728_221/1627440327667GyoYj_JPEG/movie_image.jpg"
                     class="card-img-top" alt="...">
                <div class="card-body">
                    <h5 class="card-title">영화 제목이 들어갑니다</h5>
                    <p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
                    <p>⭐⭐⭐</p>
                    <p class="mycomment">나의 한줄 평을 씁니다</p>
                </div>
            </div>
        </div>
    </div>
</div>

let mytitle='영화 제목' 으로 mytitle이라는 변수를 만들어주고
👉영화 제목이 들어갑니다 부분을 ${mytitle}로 바꿔주면 된다
지난번 1주차때 배웠던 리스트/딕셔너리 형식을 참고
let a_list=[] 순서대로 가지고 있음 각요소들이 자동으로 번호를 부여받음 0,1,2...
let a_dict={} 키와 밸류의 묶음

리스트와 딕셔너리의 조합[리스트{딕셔너리}]
customers=[{'name':'bob','age':28,'height':1.7},{'name':'john','age':22,'height':1.4}]

function을 만들었으면 그 함수가 작동할 위치에 꼭 넣어주는 걸 잊지 말자!!

예제>포스팅 박스 열고 닫기

function open_box(){
    $('#post-box').show()
}
function close_box(){
    $('#post-box').hide()
}

css에서 처음부터 박스 안보이게 하기는 display:none

.mypost {
    width: 95%;
    max-width: 500px;
    margin: 20px auto 0px auto;
    padding: 20px;
    box-shadow: 0px 0px 3px 0px gray;
    
    display: none;
}

예제>

function q1() {
            // 1. input-q1의 입력값을 가져온다. $('# .... ').val() 이렇게!
            // 2. 만약 입력값이 빈칸이면 if(입력값=='')
            // 3. alert('입력하세요!') 띄우기
            // 4. alert(입력값) 띄우기
            let a= $('#input-q1').val();
            if(a==''){
                alert('입력하세요!')
            }else{
                alert(a)//여기에 'a'하면 a나온다
            }
        }
function q2() {
            // 1. input-q2 값을 가져온다.
            // 2. 만약 가져온 값에 @가 있으면 (includes 이용하기 - 구글링!)
            // 3. info@gmail.com -> gmail 만 추출해서 ( .split('@') 을 이용하자!)
            // 4. alert(도메인 값);으로 띄우기
            // 5. 만약 이메일이 아니면 '이메일이 아닙니다.' 라는 얼럿 띄우기
            let a= $('#input-q2').val();
  			//console.log(a.includes('@'))로 확인가능
            if(a.includes('@')==true){
                alert(a.split('@')[1].split('.')[0])
            }else{
                alert('이메일이 아닙니다')
            }
   function q3() {
            // 1. input-q3 값을 가져온다. let txt = ... q1, q2에서 했던 걸 참고!
            // 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${txt}</li>`) 요렇게!
            // 3. 만들어둔 temp_html을 names-q3에 붙인다.(jQuery의 $('...').append(temp_html)을 이용하면 굿!)
            let a=$('#input-q3').val();
            let temp_html=`<li>${a}</li>`
            $('#names-q3').append(temp_html)//여기도 ''쓰면 안됨.. 이거 어떻게 구분하지? 밖에서 불러온거만?
        }

        function q3_remove() {
            // 1. names-q3의 내부 태그를 모두 비운다.(jQuery의 $('....').empty()를 이용하면 굿!)
             $('#names-q3').empty()
        }

JSON형식= 리스트+딕셔너리

클라이언트-서버 요청

  • get type 데이터를 조회 ➡2주차에서 사용
  • post typle 데이터를 생성, 업데이트, 삭제 요청

Ajax

Ajax는 jQuery를 임포트한 페이지에서만 동작 가능합니다

$.ajax({
 type: "GET", // GET 방식으로 요청한다.
 url: "http://spartacodingclub.shop/sparta_api/seoulair",
 //open API 주소
 data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
 success: function(response){ // 성공하면, 서버에서 준 결과를 response라는 변수에 담아서 함수를 실행한다
   console.log(response) // 개발자도구에서 확인, 서버에서 준 결과를 이용해서 나머지 코드를 작성
 }
})

예제>

  1. 모든 구의 미세먼지 값을 나타내기+기준보다 높으면 빨간색으로 표시
<!doctype html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>jQuery 연습하고 가기!</title>

    <!-- jQuery를 import 합니다 -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <style type="text/css">
        div.question-box {
            margin: 10px 0 20px 0;
        }
        .bad {
            color: red;
            font-weight: bold;
        }
    </style>

    <script>
        function q1() {
            // 여기에 코드를 입력하세요
            $('#names-q1').empty();//버튼 누를 때마다 싹지우고 다시 업데이트
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/seoulair",
                data: {},
                success: function (response) {
                    let rows = response["RealtimeCityAir"]["row"];//몇번짼지 모르니까 그냥 알고 있는 이름으로 가져옴 어디 안에 누구
                    for (let i = 0; i < rows.length; i++) {
                        let gu_name = rows[i]['MSRSTE_NM'];
                        let gu_mise = rows[i]['IDEX_MVL'];

                        let temp_html = ''//문자열을 일단 만들어만 둔다

                        if (gu_mise > 70) {
                            temp_html = `<li class="bad">${gu_name} : ${gu_mise}</li>`
                        } else {
                            temp_html = `<li>${gu_name} : ${gu_mise}</li>`
                        }
                        
                        $('#names-q1').append(temp_html);
                    }
                }
            })
        }
    </script>

</head>

<body>
    <h1>jQuery+Ajax의 조합을 연습하자!</h1>

    <hr />

    <div class="question-box">
        <h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
        <p>모든 구의 미세먼지를 표기해주세요</p>
        <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
        <button onclick="q1()">업데이트</button>
        <ul id="names-q1">
        </ul>
    </div>
</body>

</html>

2.따릉이 현황+5대미만 빨간색

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

<head>
    <meta charset="UTF-8">
    <title>jQuery 연습하고 가기!</title>
    <!-- jQuery를 import 합니다 -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <style type="text/css">
        div.question-box {
            margin: 10px 0 20px 0;
        }

        table {
            border: 1px solid;
            border-collapse: collapse;
        }

        td,
        th {
            padding: 10px;
            border: 1px solid;
        }
		.urgent {
            color: red;
            font-weight: bold;
        }

    </style>

    <script>
        function q1() {
            $('#names-q1').empty();
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/seoulbike",
                data: {},
                success: function (response) {
                    let rows = response["getStationListList"]["row"];//왜 여긴 ""??
                    for (let i = 0; i < rows.length; i++) {
                        let rack_name = rows[i]['stationName'];
                        let rack_cnt = rows[i]['rackTotCnt'];
                        let bike_cnt = rows[i]['parkingBikeTotCnt'];//왜 여긴 ''
                       /* let temp_html = `<tr>
                                            <td>${rack_name}</td>
                                            <td>${rack_cnt}</td>
                                            <td>${bike_cnt}</td>
                                        </tr>`//붙여줄 곳이랑 형태 똑같이 따오면 됨 (#names-q1)*/
                        let temp_html = '';
                        if (bike_cnt < 5) {
                            temp_html = `<tr class="urgent">
                                <td>${rack_name}</td>
                                <td>${rack_cnt}</td>
                                <td>${bike_cnt}</td>
                              </tr>`
                        } else {
                            temp_html = `<tr>
                                <td>${rack_name}</td>
                                <td>${rack_cnt}</td>
                                <td>${bike_cnt}</td>
                              </tr>`
                        }
                        
                        
                        $('#names-q1').append(temp_html);
                    }
                }
            })
        }
    </script>

</head>

<body>
    <h1>jQuery +Ajax의 조합을 연습하자!</h1>

    <hr />

    <div class="question-box">
        <h2>2. 서울시 OpenAPI(실시간 따릉이 현황)를 이용하기</h2>
        <p>모든 위치의 따릉이 현황을 보여주세요</p>
        <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
        <button onclick="q1()">업데이트</button>
        <table>
            <thead>
                <tr>
                    <td>거치대 위치</td>
                    <td>거치대 수</td>
                    <td>현재 거치된 따릉이 수</td>
                </tr>
            </thead>
            <tbody id="names-q1">
            </tbody>
        </table>
    </div>
</body>

</html>
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="UTF-8">
    <title>JQuery 연습하고 가기!</title>
    <!-- JQuery를 import 합니다 -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    
    <style type="text/css">
      div.question-box {
        margin: 10px 0 20px 0;
      }
      div.question-box > div {
        margin-top: 30px;
      }
      
    </style>

    <script>
      function q1() {
        $.ajax({
          type: "GET",
          url: "http://spartacodingclub.shop/sparta_api/rtan",
          data: {},
          success: function(response){
              let imgurl = response['url'];
            //걍 리스트라서 ''쓴건가? 리스트 요소부를때와 딕셔너리 요소 부를때의 차이인 것 같음
              $("#img-rtan").attr("src", imgurl);
			//$("#아이디값").attr("src", 이미지URL);
              let msg = response['msg'];
              $("#text-rtan").text(msg);
            //$("#아이디값").text("바꾸고 싶은 텍스트");
            }
          })
      }
    </script>

  </head>
  <body>
    <h1>JQuery+Ajax의 조합을 연습하자!</h1>

    <hr/>

    <div class="question-box">
      <h2>3. 르탄이 API를 이용하기!</h2>
      <p>아래를 르탄이 사진으로 바꿔주세요</p>
      <p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
      <button onclick="q1()">르탄이 나와</button>
      <div>
        <img id="img-rtan" width="300" src="http://spartacodingclub.shop/static/images/rtans/SpartaIcon11.png"/>
        <h1 id="text-rtan">나는 ㅇㅇㅇ하는 르탄이!</h1>
      </div>
    </div>
  </body>
</html>

2주차 숙제>

이번 숙제는 5초컷이었당 희희.. 힘드렁..

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

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>
    <link href="https://fonts.googleapis.com/css2?family=Gaegu&display=swap" rel="stylesheet">
    <title>스파르타코딩클럽 | 부트스트랩 연습하기</title>

    <style>
        * {
            font-family: 'Gaegu', cursive;
        }

        .mort {

            width: 100%;
            height: 250px;

            background-image: url("https://i.pinimg.com/originals/c0/d9/88/c0d98850bf6f5fe46f7f530aa6647b6f.png");
            background-size: cover;
            background-position: center 33%;

            color: white;

            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

        }

        .wrap {
            max-width: 500px;
            width: 95%;
            margin: 20px auto 0px auto;

            box-shadow: 0 0 5px 0 gray;
            padding: 20px;

        }

        .buttons {
            margin-top: 20px;
        }

        .cards {
            /*background-color: hotpink;*/
            max-width: 500px;
            width: 95%;
            margin: 20px auto 0px auto;

            display: flex;
            flex-direction: column;
            justify-content: center;
            /*계속 카드를 작게 만들어서 중앙으로 보내버리는 이유가..?
            align-items: center;*/
        }

        .card {
            margin-bottom: 10px;
        }
    </style>
    <script>
        $(document).ready(function () {
      //버튼을 클릭해서 하는게 아니라 로딩이 되면 업데이트가 되는..
            $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                data: {},
                success: function (response) {

                    let temp = response['temp']

                    $("#temp").text(temp);

                    // console.log(response)
                }
            })
        });
    </script>
</head>

<body>

<div class="mort">
    <h1>모트 팬명록</h1>
    <p>현재 기온 : <span id="temp">00.0</span></p>
</div>
<div class="wrap">

    <div class="form-floating mb-3">
        <input type="url" class="form-control" id="floatingInput" placeholder="http://">
        <label for="floatingInput">닉네임</label>
    </div>
    <div class="form-floating">
        <textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea"
                  style="height:100px"></textarea>
        <label for="floatingTextarea">응원 댓글</label>
    </div>
    <div class="buttons">
        <button type="button" class="btn btn-dark">응원 남기기</button>
    </div>

</div>

<div class="cards">
    <div class="card">
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>너무 귀여워요!</p>
                <footer class="blockquote-footer">King Julien</footer>
            </blockquote>
        </div>
    </div>
    <div class="card">
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>너무 귀여워요!</p>
                <footer class="blockquote-footer">King Julien</footer>
            </blockquote>
        </div>
    </div>
    <div class="card">
        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <p>너무 귀여워요!</p>
                <footer class="blockquote-footer">King Julien</footer>
            </blockquote>
        </div>
    </div>
</div>


</body>

</html>


💡2주차 회고

감으로 때려 맞추는 듯한 기분이 들어서 너무 찝찝한데 다시 들어보고 풀어보면 그래도 나름 알고 있는듯하기도 하고 문제는 정확히 모르겠는 부분들을 다음주엔 알게 되길..

  • ''와 ""의 구분
  • 리스트와 딕셔너리의 다양한 조합
  • ajax는 jquery랑 뭐가 다른가? 자바스크립트 안에 jquery안에 ajax?
profile
looooggi

0개의 댓글