2주차 - JQuery와 Ajax

자유의여신·2022년 5월 1일
0

웹개발 요약

목록 보기
2/5

JQuery란?

  • HTML의 요소들을 조작하는, 편리한 Javascript를 미리 작성해둔 라이브러리

  • 미리 작성된 Javascript 코드를 가져오는 방법 : import
    : 와 사이에 아래 소스 입력

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  • body에 id="url"(예)로 정의하고 이 값을 script에서 사용함

  • script에서는 아래와 같이 사용

let mytitle="타이타닉"

$('#url').val()
$('#url').hide()
$('#url').show()

let temp_html=`<button>${mytitle}</button>`
$('#card-box').append(temp_html)
  • 정리

    CSS는 body에서 class="card"와 같이 정의하고
    style에서 .class{} 로 불러서 사용함

변수를 부를때는 ${변수명}으로 부름

body에 있는 것을 부를 때는 $('#id명')으로 부름

서버-클라이언트 통신

Ajax 기본 골격

  • 서버의 API 정보를 가져와서 활용하겠다
    : function에서 Ajax call을 하면 된다!
$.ajax({
  type: "GET",
  url: "여기에URL을입력",
  data: {},
  success: function(response){
    console.log(response)
  }
})
$.ajax({
  type: "GET", // GET 방식으로 요청한다.
  url: "http://spartacodingclub.shop/sparta_api/seoulair",
  data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
  success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
    console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
  }
})

Ajax 호출 연습 예제

  • script 내 funtion에서 ajax 호출(서버로부터 값을 가져옴)을 한다. (기본 골격 활용)
  • 서버로부터 받은 내용으로 temp_html을 생성해서 붙여주는 것과
  • empty는 ajax 호출 전에 불러줌
  • 조건에 따라 css를 입혀주는 것
<!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;
        }
    </style>

    <script>
        function q1() {
            $('#names-q1').empty()
                $.ajax({
                    type: "GET",
                    url: "http://spartacodingclub.shop/sparta_api/seoulair",
                    data: {},
                    success: function (response) {
                        console.log(response['RealtimeCityAir'])
                        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>60){
                                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>

이미지, text 바꾸기

  • 이미지 바꾸기 : $("#아이디값").attr("src", 이미지URL);
  • 텍스트 바꾸기 : $("#아이디값").text("바꾸고 싶은 텍스트");
  • 이미지URL과 텍스트에 변수를 넣어도 됨

화면 로딩 후 호출하기

  • script에 작성
<script>
        $(document).ready(function () {
            alert('다 로딩됐다!')
            // 여기에 함수 작성(Ajax 호출 등) or 함수호출
        });
    </script>

서버로부터 값을 가져와서 setting

<head>
<script>
        $(document).ready(function () {
           $.ajax({
                type: "GET",
                url: "http://spartacodingclub.shop/sparta_api/weather/seoul",
                data: {},
                success: function (response) {
                    // console.log(response)
                    let temp = response['temp']
                    console.log(temp)
                    $('#temp').text(temp)
                    }
            })
        });

    </script>

</head>

<body>
<div class="mytitle">
    <h1> 이하이 팬명록 </h1>
    <p>현재기온 : <span id="temp"></span></p>
</div>

회고록

강의를 2번째 수강하니 확실히 다르다.

  • Jquery도 이번에 제대로 이해했다. Javascript의 lib이고, import하는 법 등 다시 정리되었다.
  • 우선 Ajax호출에 대한 개념과 사용방법, 사용 위치를 제대로 이해했다.
  • 코딩하면서 '' or # or [''] 와 같은 것들을 안적어서 에러가 나는 경우가 많다.
  • 화면 로딩 후 호출하는 것과, 서버로부터 값을 가져와서 setting하고 싶으면 그 부분을 span으로 묶어서 id를 부여하여 text로 바꿔줄 수 있는 것이 재미있었다.
profile
나만의 색깔

0개의 댓글