web 기초/AJAX

Algo rhythm·2022년 6월 9일
0

web 기초

목록 보기
13/15

AJAX(Asynchronous Javascript And XML)

JavaScript를 사용한 비동기 통신, 클라이언트와 서버 간에 XML데이터를 주고 받는 기술
=> 자바스크립트를 통해서 서버에 데이터를 요청하는 것

  • AJAX는 비동기 방식

비동기

  • 웹 페이지를 리로드하지 않고도 데이터를 불러오는 방식

동기

  • 데이터를 불러올 때 순서에 맞게 일을 진행
  • 먼저 순서가 진행되지 않으면 이후의 진행이 불가능

예시

  • 동시에 접근하여 일처리를 한다 => 비동기 like 스타크래프트 멀티 태스킹
  • 순서대로 접근하여 하나씩 처리한다 => 동기

클라이언트

  • 서버에서 정보를 가져와 사용자에게 보여줄 수 있는 소프트웨어
  • EX) 웹 브라우저, APP

AJAX 장점

  • 웹페이지의 속도향상
  • 서버의 처리가 완료될 때까지 기다리지 않고 처리 가능
  • 서버에서 Data만 전송하면 되므로 전체적인 코드의 양의 감소
  • 기존 웹에서는 불가능했던 다양한 UI 가능

AJAX 단점

  • 히스토리 관리 없음
  • 페이지 이동없는 통신으로인한 보안상의 문제
  • 연속으로 데이터를 요청하면 서버 부하 증가
  • XMLHttpRequest를 통해 통신하는 경우, 사용자에게 아무런 진행 정보가 주어지지 않음(요청이 완료되지 않았는데 사용자가 페이지를 떠나거나 오작동할 우려가 발생
  • AJAX를 쓸 수 없는 브라우저에 대한 문제
  • HTTP 클라이언트의 기능이 한정
  • 지원하는 Charset이 한정
  • Script로 작성되므로 디버깅 곤란
  • 동일-출처 정책으로 인하여 다른 도메인과의 통신불가(Cross-Domain문제)

CORS

  • 보안상의 이유로 브라우저에서 제한

AJAX 예시

<!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>
  <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
    crossorigin="anonymous"></script>
</head>
<body>
  <script>
    $(function () {
      $('#get_data_button').click(function() {
        // GET 방식
        // $('#demo').load('ajax_info.txt');
        
        // JSON 파일을 불러온 후 다음 명령을 실행
        $.getJSON('people.json', function (json) {
          console.log(json);
          // json 파일의 내용을 텍스트로 변환하여 div에 입력
          $('#demo').html(JSON.stringify(json)); 
          // json 파일의 내용 중 이름과 스킬만 출력하여 입력
          $('#demo').html(`${json.name} : ${json.skill}`);
        });
      });
    });
  </script>
  <div id="demo"></div>
  <button id="get_data_button">get data</button>
</body>
</html>

fetch 익히기

<!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>
  <script>
    function loadDoc() {
      
      console.log('start');

      // 비동기 == 오래걸리는 동작
      fetch('people.json')
        // .then(function(response) {
        //   return response.text();
        // })

        // 화살표 함수(Arrow function)
        // 람다식 (lambda exepression)
        .then(response => response.json()) // 기다렸다가 여기서 처리
        .then(json => {
          console.log(json);

          let result = '${json.name} : ${json.skill}';

          document.getElementById('demo').innerHTML = result;
          document.getElementById('json').innerHTML = JSON.stringify(json);
        });
      console.log('end');
    }
  </script>
  <div id="demo"></div>
  <div id="json"></div>
  <button onclick="loadDoc()">get data</button>
</body>
</html>

fetch의 첫 번째 인자 : url
fetch의 두 번째 인자 : 옵션객체

  • 콘솔 로그 먼저 실행한 후에 응답을 실행

실습 - 영화제목만 가져와서 리스트 추가

<!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>
  <script src="https://code.jquery.com/jquery-3.6.0.js" 
    integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
    crossorigin="anonymous"></script>
</head>

<body onload="loadData()">
  <script>
    function loadData() {
      fetch('https://jsonplaceholder.typicode.com/todos/')
        .then(response => response.json())
        .then(jsonArray => {
          // for (let i = 0; i < jsonArray.length; i++)
          let $list = $('#list');
          jsonArray.forEach((data, i) => {
            $list.append(`<li>${i} : ${data.title}</li>`);
          })
          console.log(jsonArray);
        });
    } 
  </script>
  <ul id="list">
  </ul>
</body>
</html>

  • 리스트로 구성된 원본 데이터

  • foreach 문을 활용하여, 원소의 위치와 원소의 일부 내용을 html 리스트에 추가
    -- foreach(원소가 될 변수 이름, 원소의 인덱스)

실습2 - 영화리뷰 리스트로 추가

<!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>
  <script src="https://code.jquery.com/jquery-3.6.0.js" 
    integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
    crossorigin="anonymous"></script>

  <style>
    .card {
      /* Add shadows to create the "card" effect */
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
      transition: 0.3s;
      margin-bottom: 10px;
      width: 600px;
    }

    /* On mouse-over, add a deeper shadow */
    .card:hover {
      box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
    }

    /* Add some padding inside the card container */
    .container {
      padding: 2px 16px;
    }
  </style>
</head>

<body onload="loadData()">
  <script>
    function moveCommentsPage(postId) {
      console.log(postId);
      // 페이지 이동
      document.location.href = `exam4_comments.html?id=${postId}`;
    }

    function loadData() {
      fetch('https://jsonplaceholder.typicode.com/posts/')
        .then(response => response.json())
        .then(jsonArray => {
          // for (let i = 0; i < jsonArray.length; i++)
          let $list = $('#list');
          jsonArray.forEach((data, i) => {

            // 위의 링크에서 받아온 정보, 리스트의 원소를 하나씩 받아서 'card'클래스 div를 추가하며 입력
            $list.append(`<div class="card"token interpolation">${data.id})">
                <div class="container">
                  <h4><b>${data.title}</b></h4>
                  <p>${data.body}</p>
                </div>
              </div>`);
          })
          console.log(jsonArray);
        });
    } 
  </script>

  <div id="list">
    <!-- <div class="card">
      <div class="container">
        <h4><b>John Doe</b></h4>
        <p>Architect & Engineer</p>
      </div>
    </div> -->
  </div>
</body>
</html>
  • 영화제목과 영화에 대한 리뷰를 list 태그에 추가
  • 클릭하면 moveCommentsPage 함수에 의해 해당 영화에 대한 리뷰만 남긴 웹 페이지로 이동

영화 포스터 받아서 웹 페이지에 출력

<!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>
  <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
    crossorigin="anonymous"></script>

  <style>
    .card {
      /* Add shadows to create the "card" effect */
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
      transition: 0.3s;
      margin: 10px;
      width: 330px;
      height: 550px;
      display: inline-block;
      float: left;
    }

    /* On mouse-over, add a deeper shadow */
    .card:hover {
      box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
    }

    /* Add some padding inside the card container */
    .container {
      padding: 2px 16px;
    }

    img {
      width: 100%;
      margin-top: 15px;
    }

    h4 {
      text-align: center;
      font-size: 20px;
    }
  </style>
</head>

<body onload="loadData()">
  <script>
    function moveCommentsPage(id) {
      console.log(id);
      // 페이지 이동
      document.location.href = `exam6_one_movie.html?id=${id}`;
    }

    function loadData() {
      fetch('https://api.themoviedb.org/3/movie/upcoming?api_key=a64533e7ece6c72731da47c9c8bc691f&language=ko-KR&page=1')
        .then(response => response.json())
        .then(jsonArray => {
          // for (let i = 0; i < jsonArray.length; i++)
          let movie = jsonArray.results;
          movie.forEach((data, i) => {
            $('#list').append(`<div class="card"token interpolation">${data.id})">
                <div class="container">
                  <img src="https://image.tmdb.org/t/p/w500${data.poster_path}" alt="poster_image">
                  <h4><b>${data.title}</b></h4>
                </div>
              </div>`);
          })
          console.log(jsonArray);
        });
    } 
  </script>

  <div id="list">
  </div>

</body>
</html>
profile
배운 건 써 먹자

0개의 댓글