본문 바로가기

코딩공부/WEB3 - Ajax

[5] 글 목록 ajax 로 구현하기

데이터와 애플리케이션(로직) 구분

프로그래머는 데이터와 로직데이터와 애플리케이션을 구분한다.

 

index.html 은 데이터와 로직이 섞여 있다.

'글 목록' 은 데이터이다. 즉, 바뀔 수 있는 부분이다.

index.html - 데이터와 로직

 

데이터와 로직을 구분하고 싶다. 데이터가 변경되었다고 애플리케이션을 고치는 상황이 나오지 않는다.

 

  1. 따라서 데이터의 성격인 부분을 따로 떼어서 새로운 파일(list)로 만든다.
  2. ol 태그에 id 값을 설정 
  3. fetch API를 이용해서 글 목록을 가져오기
<!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;
        })
      })
    }
    if(location.hash){
      fetchPage(location.hash.substr(2)); //substr 문자열 자르기
    }else{
      fetchPage('welcome');
    }
    fetch('list').then(function(response){ //글 목록 가져오기
      response.text().then(function(text){
        document.querySelector('#nav').innerHTML = text;
      })
    })
  </script>
</head>
<body>
  <h1><a href="#!welcome">Javakong Cafe</a></h1>
  <input type="button" value="night" onclick="nightDayHandler(this)">
  <div id="grid">
      <ol id="nav"> <!-- 글 목록이 들어갈 위치 -->
      </ol>
    <article>
    </article>
  </div>
</body>
</html>

데이터(글목록 내용)와 로직을 구분

 

리팩토링

list 파일 내에 중복이 존재한다.

<li><a href="#!coffee" onclick="fetchPage('coffee')">커피</a></li>
<li><a href="#!tea" onclick="fetchPage('tea')">차</a></li>
<li><a href="#!bread" onclick="fetchPage('bread')">빵</a></li>

 

중복을 모두 제거하고 본질적인 내용만 컴팩트하게 남기고 싶다...?

coffee,tea,bread

 

fetch 로 받아오는 response의 text 값의 데이터 타입은 string 인 것을 확인할 수 있다.

console.log(typeof text);

 

문자열에 있는 콤마(,)를 구분자로 하여 각 단어를 배열로 저장

javascript string to array
how to remove front back white space in string javascript

split() 함수

 

 

split 메소드를 통해 list 파일의 내용을 불러와 배열로 저장한다.

<!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;
        })
      })
    }
    if(location.hash){
      fetchPage(location.hash.substr(2)); //substr 문자열 자르기
    }else{
      fetchPage('welcome');
    }
    fetch('list2').then(function(response){ //글 목록 가져오기
      response.text().then(function(text){
        console.log(typeof text);	// 데이터 타입이 문자열인 것 확인
        var items = text.split(",");	// ,를 기준으로 문자열을 잘라서 배열로 저장
        console.log(items);	// 각 단어가 배열로 저장된 것 확인 - 맨 마지막 단어에 쓰레기값이 들어가있음
        var navtext = '';
        for (var value of items){
          console.log(value);
          value = value.trim();	// 단어에 불필요한 공백을 제거 - 쓰레기값없애기
          navtext += "<li><a href=\"#!"+value+"\" onclick=\"fetchPage('"+value+"')\">"+value+"</a></li>"

        }
        console.log(navtext);
        document.querySelector('#nav').innerHTML = navtext;

      })
    })
  </script>
</head>
<body>
  <h1><a href="#!welcome">Javakong Cafe</a></h1>
  <input type="button" value="night" onclick="nightDayHandler(this)">
  <div id="grid">
      <ol id="nav"> <!-- 글 목록이 들어갈 위치 -->
      </ol>
    <article>
    </article>
  </div>
</body>
</html>

 

 

 

 

 

 

 

 

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

[6] fetch API polyfill  (0) 2019.09.13
[4] 초기 페이지 구현 - 해쉬뱅(HashBang)#!  (0) 2019.09.11
[3] Ajax 의 적용  (0) 2019.09.10
[2] fetch API  (0) 2019.09.09
[1] Ajax 로 얻을 수 있는 장점  (0) 2019.09.09