Asynchronous Java And XML


고정적인 내용과 변동성이 있는 내용을 구분하여 웹페이지의 성능을 향상시키는 방식

변동성이 있는 내용 → ajax파일화

AJAX의 통신 원리

[Javascript] 비동기 통신(Ajax)를 하는 방법

Ajax를 구현하는 여러 방법중 Fetch API를 사용해보자.

Fetch API

<input type="button" value="fetch" onclick="
fetch('css.html').then(function (response) { // 익명함수 형태
    response.text().then(function (text) {
        alert(text);
        document.querySelector('article').innerHTML = text;
    })
})">

// fetch를 통해 정보를 요청하면 그 아래 명령어들을 실행함

fetch(~).then(function(response객체) {
}); // function을 호출할 때 첫번째 인자로 response객체를 주게 되어 있다.

response

fetch(~).then(function(response객체){};

fetch를 통해 요청했을 때 웹서버가 응답한 결과를 담은 객체이다.

<!doctype html>
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
  <script src="<https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js>"></script>
  <script src="colors.js"></script>
</head>
<body>
  <h1><a href="index.html">WEB</a></h1>
  <input id="night_day" type="button" value="night" onclick="
    nightDayHandler(this);
  ">
  <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;          
      }) 
    })
	  } // 인자로 name -> 요청한 결과 인자에 대한 text값을 받음 -> 인자로 text를 넣어 current
// document 내 article query를 선택하여 안에 text를 대입
</script>
</body>
</html>

Hash

hash값(북마크 기능)에 따라 ajax로 다른 페이지를 로드해서 시작되는 페이지를 세팅할 수 있다.

hash : url 파라미터와 비슷한 역할을 한다. #~를 하면 id를 찾아준다.

#은 기본적으로 북마크 기능이기 때문에 hash기능과 구분하기 위해 !(bang)을 붙여준다.

→ #! = hash bang