본문 바로가기
DEV/Web 개발

파이썬 웹 프로그래밍 :: jQuery, Ajax를 활용한 웹 화면 생성

by 올커 2022. 7. 22.

파이썬 웹 프로그래밍_jQuery, Ajax 웹 화면 생성


들어가면서..

 본 포스팅을 통해 jQuery와 Ajax에 대한 기본 개념을 설명하고자 한다.

1. jQuery

· HTML의 요소를 조작하기 위한 JavaScript를 미리 작성해 둔 라이브러리 중 하나
  간단한 코드, 브라우저 간 호환성을 개선

//Javascript
	document.getElementById("element").style.display = "none";

//jQuery로 보다 직관적이고 간단하게 표현 가능
	$('#element').hide();


· 사용 전 import가 필요하다  →  홈페이지(*링크)의 jQuery CDN부분 참고

<https://www.w3schools.com/jquery/jquery_get_started.asp>

<!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>
 
 ...

· jQuery에서는 id값을 통해 특정 버튼/인풋박스/div/..등을 가리친다.

// 크롬 개발자도구 콘솔창에서 쳐보기
// id 값이 url인 곳을 가리키고, val()로 값을 가져온다.
$('#url').val();

// 입력할때는?
$('#url').val('이렇게 하면 입력이 가능하지만!');


// 크롬 개발자도구 콘솔창에 쳐보기
// id 값이 post-box인 곳을 가리키고, hide()로 안보이게 한다.
$('#post-box').hide();

// show()로 보이게 한다.
$('#post-box').show();

· 태그 내 동적으로 html을 삽입하고 싶을 때 사용하는 방법

1) 버튼을 클릭할 때 카드 추가하기

// 주의: 홑따옴표(')가 아닌 backtick(`)으로 감싸야 합니다.
// backtick을 사용하면 문자 중간에 Javascript 변수 삽입 가능

let title = '영화 제목';

// temp_html에 대한 정의
let temp_html = `<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">${title}</h5>
                            <p class="card-text">여기에 영화에 대한 설명이 들어갑니다.</p>
                            <p>⭐⭐⭐</p>
                            <p class="mycomment">나의 한줄 평을 씁니다</p>
                        </div>
                    </div>
                </div>`;
                
$('#cards-box').append(temp_html);

2) 버튼 클릭시 박스 여닫기

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

<head>
    ...
    <title>스파르타 피디아</title>
    ...
    <style>
        ...
    </style>
    
    <script>               // 열기/닫기 function 정의
        function open_box(){         //'open_box'에 열기 기능
            $('#post-box').show()
        }
        function close_box(){         //'close_box'에 열기 기능
            $('#post-box').hide()
        }
    </script>
</head>

<body>
<div class="mytitle">
    <h1>내 생애 최고의 영화들</h1>
    <button onclick="open_box()">영화 기록하기</button>     // onclick="open_box()"로 위의 기능과 연결
</div>
<div class="mypost" id="post-box">
    <div class="form-floating mb-3">
        ...
    </div>
    <div class="input-group mb-3">
        ...
    </div>
    <div class="form-floating">
        ...
    </div>
    <div class="mybtns">   // onclick="close_box()" 를 통해 function과 연결됨
        <button type="button" class="btn btn-dark">기록하기</button>
        <button onclick="close_box()" type="button" class="btn btn-outline-dark">닫기</button>
    </div>
</div>
<div class="mycards">
    ...
</div>
</body>

</html>

· jQuery 연습 1 : https://drive.google.com/file/d/1XJoYh4_FTiu-MVQpaCM6vJ5zXnIKcdCp/view?usp=sharing 

 

jquery01.html

 

drive.google.com

2. 서버 → 클라이언트, JSON의 이해 

· JSON은 Key:Value로 이루어져 있으며 자료형 Dictionary와 매우 유사
· JSONView를 통해 예쁘게 Json파일을 볼 수 있음 (※ 참고 : 링크)
· 클라이언트 → 서버 : Get/Post 요청 이해하기
  1) Get : 데이터 조회(Read)를 요청할 때
  2) Post : 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청할 때
· Get 방식으로 데이터를 전달하는 방법

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

예시) google.com/search?q=아이폰&sourceid=chrome&ie=UTF-8
위 주소는 google.com의 search 창구에 다음 정보를 전달합니다!
q=아이폰                     (검색어)
sourceid=chrome       (브라우저 정보)
ie=UTF-8                    (인코딩 정보)

 

3. Ajax 

· Ajax는 jQuery를 임포트한 페이지에서만 동작 가능
· Ajax 기본 골격

$.ajax({
  type: "GET",     // Get방식으로 요청한다
  url: "여기에URL을입력",
  data: {},        // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두기)
  success: function(response){    // 서버에서 준 결과를 response라는 변수에 담음
    ...      // 서버에서 준 결과를 이용해서 나머지 코드를 작성
  }
})

· 샘플 - 모든 구의 미세먼지 값을 찍어보기

$.ajax({
  type: "GET",
  url: "http://spartacodingclub.shop/sparta_api/seoulair",
  data: {},
  success: function (response) {
    let mise_list = response["RealtimeCityAir"]["row"];
    for (let i = 0; i < mise_list.length; i++) {
      let mise = mise_list[i];
      let gu_name = mise["MSRSTE_NM"];
      let gu_mise = mise["IDEX_MVL"];
      console.log(gu_name, gu_mise);
    }
  }
});

 (1) ajax 연습 1 : https://drive.google.com/file/d/1bdVvIkgRiWrQqhKqyvAObvLJ2F8tzo7d/view?usp=sharing
 (2) ajax 연습 2 : https://drive.google.com/file/d/1rDlDV_I_URnTxEY770Eo24Wm0gCu7-WS/view?usp=sharing
 (3) ajax 연습 3 : https://drive.google.com/file/d/1moEr8gbJwApG6T9FQmKXmWgrxkrPk-J6/view?usp=sharing 

 

ajax01.html

 

drive.google.com

 

ajax02.html

 

drive.google.com

 

ajax03.html

 

drive.google.com

  ※ 참고. ajax03.html 작성시 주의

      - 이미지 바꾸기

$("#아이디값").attr("src", 이미지URL);

      - 텍스트 바꾸기

$("#아이디값").text("바꾸고 싶은 텍스트");

      - 로딩 후 바로 실행

$(document).ready(function(){
	////
})

 

반응형

댓글