본문 바로가기

코딩공부/WEB3 - Ajax

[3] Ajax 의 적용

Ajax 적용

목표 : Ajax 를 사용하여 각 목록의 본문 내용만 웹서버에게 요청하여 브라우저에 출력

 

<!doctype html>
<html>
<head>
  <title>JAVA kong Cafe</title>
  <meta charset="utf-8">
  <!-- <link rel="stylesheet" href="style.css"> -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="./colors.js"></script>
</head>
<body>
  <h1><a href="index.html">Javakong Cafe</a></h1>
  <input type="button" value="night" onclick="nightDayHandler(this)">
  <div id="grid">
      <ul>
        <li><a onclick="fetch('coffee').then(function(response){
          response.text().then(function(text){
            document.querySelector('article').innerHTML = text;
          })
        })
        ">커피</a></li>
        <li><a onclick="fetch('tea').then(function(response){
          response.text().then(function(text){
            document.querySelector('article').innerHTML = text;
          })
        })
        "></a></li>
        <li><a onclick="fetch('bread').then(function(response){
          response.text().then(function(text){
            document.querySelector('article').innerHTML = text;
          })
        })
        "></a></li>
      </ul>
    <article>

    </article>
  </div>
</body>
</html>

Ajax 적용 - 각 파일을 웹서버로 부터 다운받는 것 확인

 

리팩토링 - 함수화

현재 각 a 태그의 onclick 이벤트에 fecth() 코드를 각각 집어넣어 중복이 존재한다.

<!doctype html>
<html>
<head>
  <title>JAVA kong Cafe</title>
  <meta charset="utf-8">
  <!-- <link rel="stylesheet" href="style.css"> -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="./colors.js"></script>
  <script> // 리팩토링
    var fetchPage = function(filename){
      fetch(filename).then(function(response){
        response.text().then(function(text){
          document.querySelector('article').innerHTML = text;
        })
      })
    }
  </script>
</head>
<body>
  <h1><a href="index.html">Javakong Cafe</a></h1>
  <input type="button" value="night" onclick="nightDayHandler(this)">
  <div id="grid">
      <ul>
        <li><a onclick="fetchPage('coffee')">커피</a></li>
        <li><a onclick="fetchPage('tea')"></a></li>
        <li><a onclick="fetchPage('bread')"></a></li>
      </ul>
    <article>

    </article>
  </div>
</body>
</html>

 

 

 

 

 

'코딩공부 > WEB3 - Ajax' 카테고리의 다른 글