수업소개
배웠으면 써먹어야죠. 이번 시간엔 fetch API를 실전에 적용해보겠습니다.
강의
소스코드
<!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="
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>
리팩토링 - 함수화
소스코드
<!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;
})
});
}
</script>
</body>
</html>

