Ajax

  • 부분적으로 웹페이지 갱신 할 수 있도록 도와주는 것
  • 변경 가능한 부분과 불가능한 부분을 구분해서 변경 가능한 부분만 동적으로 변경 가능
  • 리스트 추가
    → list라는 파일에 기존 리스트들에 추가로 ajax라는 내용을 콤마로 구분해서 추가하면 목록 만들어짐
  • 추가한 리스트에 내용 추가
    → 추가한 리스트 이름으로 파일 만들고 내용 적으면 됨

fetch API

fetch API 기본 사용법

  • test
    1. fetch.html 파일 만들기
      <input type="button" value="fetch" onclick="
          alert('hi')
      ">
    2. CSS, HTML 그냥 파일로 만들어놓기
    3. ajax 코드 넣기
      <input type="button" value="fetch" onclick="
          fetch ('css').then (function (response){
              response.text().then(function (text){
                  alert(text);
              })
          })
      ">
      alert(text); 에 호출되도록 약속
      text 라는 변수 안에 서버가 응답한 데이터 들어 있음
    4. fetch 버튼 누르면 CSS파일 텍스트 alert에 뜸
      cf. html 텍스트 뜨게 하려면 fetch 괄호 html로 바꾸면 됨
    5. alert 대신 웹페이지 내용 바꾸기
      1) article 태그 만들기
      2) alert(text); → [변경] document.querySelector('article').innerHTML = text;
      <article>
      </article>  
      <input type="button" value="fetch" onclick="
          fetch ('css').then (function (response){
              response.text().then(function (text){
                  document.querySelector('article').innerHTML = text;
              })
          })
      ">

fetch API의 요청과 응답

  1. JavaScript 파일 서버에 응답 요청

    fetch('javascript')
  2. html 접속해 데이터 가져옴

    fetch ('html');
  3. fetch API 태그 뜯어보기
    1) fetch ('')

    • ('')로부터 전달된 저 데이터를 서버로부터 서버에게 요청하는 파일
      fetch ('html')

    2) .then ()

    • fetch API 응답 끝나면 then 이하 함수 실행 약속

      function callbackme(){
      
      }
      fetch ('html').then(callbackme);

fetch API - response 객체

  • 익명함수
    function (response){
        response.text().then(function (text){
            document.querySelector('article').innerHTML = text;
        })
    }
  • 이름이 있는 함수
    • 함수가 이름이 필요한 경우는 여기저기서 부를 때 필요
      function callbackme(){
        console.log('response end')
      }
      callbackme = function(){
        console.log('response end')
      }
      
      # 위 둘은 같은 함수
      # 두번째 모양의 함수로 익명 함수 사용 가능

  1. 이름 있는 함수를 익명 함수로 사용

    callbackme = function(){
        console.log('response end')
      }
    fetch ('html').then(callbackme);
    console.log(1)
    console.log(2)fetch ('html').then(function(){
        console.log('response end')
    });
    console.log(1)
    console.log(2)
  2. 함수 인자 값은 response 객체로
    1) 이름은 어떻게 적은 상관 없음 (aaa로 적어도 상관없음)

  3. console.log로 response객체 찍어보기

    fetch ('html').then(function (response){
      console.log(response.status);
    });

    1) status 200 → 서버가 파일 잘 찾으면 200으로 응답
    2) status 404 → 파일이 없을 때 404로 응답

  4. status로 if문 돌리기

    fetch ('html').then(function (response){
      console.log(response.status);
      if(response.status == '404'){
        alert('Not found')
      }
    });
  5. response객체는 서버가 응답한 결과 담고 있는 객체 데이터

Ajax의 적용

Ajax 적용

  1. test로 만든 fetcH API 코드 각 리스트 onclick 함수 안에 넣어주기

  2. 원문 있던 곳 지워주고 불러올 내용 들어갈 자리에 article태그 넣기

    <ol>
        <li><a onclick="
          fetch ('html').then (function (response){
            response.text().then(function (text){
              document.querySelector('article').innerHTML = text;
            })
          });
          ">HTML</a></li>
        <li><a onclick="
          fetch ('css').then (function (response){
            response.text().then(function (text){
              document.querySelector('article').innerHTML = text;
            })
          });
          ">CSS</a></li>
        <li><a onclick="
          fetch ('JavaScript').then (function (response){
            response.text().then(function (text){
              document.querySelector('article').innerHTML = text;
            })
          });
          ">JavaScript</a></li>
    </ol>
    <article>
    
    </article>

리팩토링 - 함수화

  • 중복 제거 - 함수만들기

    <ol>
        <li><a onclick="fetchPage('html')">HTML</a></li>
        <li><a onclick="fetchPage('css')">CSS</a></li>
        <li><a onclick="fetchPage('JavaScript')">JavaScript</a></li>
    </ol>
    <article>
    
    </article>
    <script>
        function fetchPage(name) {
            fetch(name).then(function (response) {
                response.text().then(function (text) {
                    document.querySelector('article').innerHTML = text;
                })
            });
        }
    </script>

초기 페이지 구현

fragment identifier를 이용한 초기 페이지 기능 구현

  1. hash (#! → 해쉬뱅)
    → 웹 주소창에 #id를 입력하는 것
    → #은 기본적으로 북마크 기능
    → 페이지 안에서 어떤 특정한 부분에 접근 (한 문단 등)

    1) hash.html 만들고 여러 문단 만들기
    2) 식별하고 싶은 곳에 id값 주기

  2. hash 값 통해서 ajax로 다른 페이지 로드해 시작되는 페이지 세팅 가능
    1) 현재 주소 상에서 샾에 해당하는 뒤에 있는 값 찾기

    <script>
        if(location.hash){
            console.log(location.hash);
        } else {
    
        }
    </script>

    2) 문자 전체에서 일부만 때는 것
    → 서브스트링 : .substr(가져올 글자의 앞 번째 수); - 1부터 시작임

    if(location.hash){
      console.log(location.hash.substr(1));
    } else {
    }

적용

  1. 각 리스트에 a hert 통해 해쉬뱅 각 리스트 이름 넣어주기
  2. 해쉬뱅을 넣어 바뀐 url 공유시 똑같은 화면 보게 하기
    1) if문으로
    if (location.hash){
      fetchPage(location.hash.substr(2));
    } else {
      fetchPage('welcome');
    }

// ajax 통해 하게되면 검색엔진 최적화가 안됨
// 그래서 현시점에서는 사용 안함
// 최근에는 pjax 사용

글목록 ajax로 구현하기

  • 데이터가 들어간 list파일 수정으로 사고 방지로 부터 자유로움
  • list파일의 중복
  1. 콤마를 구분자로 해서 나누기

  2. 반복적 작업할 때 쓰이는 "배열" 사용

  3. 배열에 담겨 있는 데이터를 반복문에 따라 꺼내서 사용 이때에는 "split" 사용

  4. 뒤 text를 innerHTML = tags;로 변경

  5. 찍히는 것을 봤으면 태그 링크 등 붙혀넣기

  6. 만약 공백이 있다고 에러뜬가면 .trim()으로 해결

    function fetchPage(name) {
      fetch(name).then(function (response) {
        response.text().then(function (text) {
          document.querySelector('article').innerHTML = text;
        })
      });
    }
    
    if (location.hash) {
      fetchPage(location.hash.substr(2));
    } else {
      fetchPage('welcome');
    }
    
    fetch('List').then(function (response) {
      response.text().then(function (text) {
        // <li><a href="#!html">HTML</a></li>
        var items = text.split(',')
        var i = 0;
        var tags = '';
        while(i < items.length){
          var item = items[i];
          item = item.trim();var tag = '<li><a href="#!'+item+'"token operator">+item+'\')">'+item+'</a></li>';
          tags = tags + tag;
          i = i + 1;
        }
        document.querySelector('#nav').innerHTML = tags;
      })
    });

fetch API polyfill

  • polypill을 이용하면 fetch API를 지원하지 않는 웹브라우저에서도 이용 가능
  • 구글에서 다운로드 후 아래 태그 적용할 html 파일에 추가
    <script src="../fetch.js"></script>

0개의 댓글

Powered by GraphCDN, the GraphQL CDN