수업소개
배웠으면 써먹어야죠. 이번 시간엔 fetch API를 실전에 적용해보겠습니다.
강의
소스코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <!doctype html> < html > < head > < title >WEB1 - Welcome</ title > < meta charset = "utf-8" > < 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=" 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 > </ p > </ body > </ html > |
리팩토링 - 함수화
소스코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <!doctype html> < html > < head > < title >WEB1 - Welcome</ title > < meta charset = "utf-8" > < 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; }) }); } </ script > </ body > </ html > |