Ajax(Asynchronous JavaScript And XML)
์ ์ฒด ํ์ด์ง๋ฅผ ์๋ก ๊ณ ์น์ง ์๊ณ ํ์ด์ง ์ผ๋ถ๋ง์ ์ํ ๋ฐ์ดํฐ๋ฅผ ๋ก๋ํ๋ ๊ธฐ๋ฒ์ด๋ค.(ํ์ผ์ ์ฌ๋๊ฒ ์๋๋ผ, ์น ์๋ฒ๋ฅผ ํตํด์ ์์
ํด์ผ ํ๋ค.)
fetch()
์น ๋ธ๋ผ์ฐ์ ์ ๊ดํธ ์์ ์ธ์๋ฅผ ์๋ฒ์๊ฒ ์๋ตํด๋ฌ๋ผ๊ณ ์์ฒญํ๋ค๋ ๋ป์ ๋น๋๊ธฐ์ API์ด๋ค.
then
์๋ฒ์ ์๋ต์ด ๋๋๋ฉด ๋ค๋ฅธ ์ผ์ ํ ์ ์๋๋ก ํด์ฃผ๋ ๊ธฐ๋ฅ
response
fetch๋ฅผ ์ฌ์ฉํด ์์ฒญํ์ ๋, ์น ์๋ฒ๊ฐ ์๋ตํ ๊ฒฐ๊ณผ๋ฅผ ๋ด๊ณ ์๋ ๊ฐ์ฒด(object)์ด๋ฉฐ, ์ด ์์ ์๋ ์ฌ๋ฌ ์์ฑ์ ํตํด ์๋ฒ์ ํต์ ์ ํ ๋ ์ด๋ ํ ์ํ๋ก ์ด๋ฃจ์ด์ก๋์ง๋ฅผ ์ ์ ์๋ค.
fetch('html').then(function(response) { response.text().then(function(text) { alert(text); document.querySelector('article').innerHTML = text; }) }) --------------------------------------------------------------------------- // ์๋ฒ์ html์ด๋ผ๋ ํ์ผ์ ์์ฒญํ๊ณ ์๋ต์ด ๋๋๋ฉด ์ต์ข ์ ์ผ๋ก ๊ฒฝ๊ณ ์ฐฝ์ด ์คํ๋๋ค. ์ด ๋ ์๋ตํด์ค ๋ฐ์ดํฐ๋ text๋ผ๋ ๋ณ์์ ๋ด๊ฒจ ์๋ค. // ์น ํ์ด์ง์ ๋ด์ฉ์ผ๋ก ๋ฐ๊พธ๊ณ ์ถ๋ค๋ฉด <body> ํ๊ทธ ์์ <article> ํ๊ทธ๋ฅผ ๋ง๋ค๊ณ , alert(text) ๋ถ๋ถ์ document.querySelector('article').innerHTML = text๋ก ๋ณ๊ฒฝ
function callbackme() { console.log('response end'); } fetch('html').then(callbackme); console.log(1); console.log(2); --------------------------------------------------------------------------- // html์ด๋ผ๋ ํ์ผ์ ์์ฒญ ํ, ์๋ต์ด ๋๋๋ฉด callbackme ํจ์๋ฅผ ์คํํด๋ผ. // html์ ์์ฒญ ํ ์ฝ์์ 1, 2๋ฅผ ์ถ๋ ฅํ๊ณ ์๋ต์ด ๋๋๋ฉด then์ผ๋ก ์ธํด 'response end'๋ฅผ ์ฝ์์ ์ถ๋ ฅํ๋ค.
์ต๋ช
ํจ์
์ด๋ฆ์ด ์๋ ํจ์๋ฅผ ๋งํ๋ฉฐ, ํ ๊ณณ์์๋ง ๋
์ ์ ์ผ๋ก ์ฌ์ฉํ๋ ํจ์๋ ๊ตณ์ด ์ ์ธํ ํ์๊ฐ ์๋ค.function callbackme() { console.log('response end'); } ---------------------------------------------------------------------------- callbackme = function() { console.log('response end'); }
// ์ ํจ์์ ์ธ๊ณผ ์๋ ํจ์์ ์ธ์ ๊ฐ์ ์๋ฏธ์ด๋ค.
fetch('html').then(function() { console.log('response end'); }); console.log(1); console.log(2);
// callbackme๋ผ๋ ํจ์์ ์ธ์ ์ญ์ ํ๊ณ , ๊ทธ์ ๊ฐ์ ์๋ฏธ์ ์ฝ๋๋ฅผ ๋ถ์ฌ๋ฃ์ผ๋ฉด ์ต๋ช ํจ์๋ก ๋ง๋ค ์ ์๋ค.
<html> <head> <script src=" https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <script src="colors.js"></script> </head> <body> <h1><a href="index.html">WEB</a></h1> <input 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; }) }); } </script> </body> </html>
// ์ค๋ณต๋๋ fetch๋ฅผ ํจ์ํ ์์ผ name์ด๋ผ๋ ๋ณ์๋ฅผ ์ ์ธํ๊ณ , fetchPage('name')์ผ๋ก ๊ฐ๋จํ๊ฒ ์ฝ๋๋ฅผ ์์ฑํ ์ ์๋ค.
// ๊ธฐ๋ณธ์ ์ธ .js, .html ํ์ผ๋ค์ ํ๋ฒ๋ง ๋ถ๋ฌ์ค๋ฉฐ html, css, javascript ํ ์คํธ ํ์ผ์ ์์ฑํ์ฌ ๋ด์ฉ๋ง ๋ฐ๋ก ๊ด๋ฆฌํ์ฌ ๋ณ๊ฒฝ๋ ์ฌํญ์ ๊ทธ ๋ ๊ทธ ๋ ๋ถ๋ฌ์จ๋ค.