오늘의 명언: 사용법부터 공부해서 흥미를 갖고 그 후 원리를 공부하여 자유도를 높이자!
학습 목표
- Ajax를 배우는 목적
웹 애플리케이션의 성능 향상
Ajax를 사용하면 웹 페이지가 다시 로드되지 않고도 데이터를 서버와 비동기적으로 주고받을 수 있다.
(즉, 불필요한 부분은 그대로 두고 필요한 부분만 reload할 수 있다.)
사용자 경험 향상
Ajax를 활용하면 사용자에게 부드러운 화면 전환과 실시간 업데이트를 제공한다.
서버 요청의 최적화
필요한 데이터만 서버로 요청하고 받아올 수 있습니다. 이로써 불필요한 데이터의 전송을 줄이고 네트워크 트래픽을 최적화할 수 있다.
웹 애플리케이션의 동적성 강화
Ajax를 통해 동적으로 데이터를 로드하고 화면을 업데이트할 수 있으므로 웹 애플리케이션의 기능을 향상시킬 수 있다.
개념 설명 필요
<!DOCTYPE html>
<html>
<body>
<article></article>
<input
type="button"
value="fetch"
onclick="
fetch('html') //
.then((response) => response.text() //
.then((text) => {
document.querySelector('article').innerHTML = text;
}))
"
/>
</body>
</html>
fetch() 메서드를 통해 html 파일에서 데이터를 response객체 형태로 가져왔다.
최종적으로 text에는 서버로부터 제공받은 데이터가 저장되어 있다.
<!DOCTYPE html>
<html lang="en">
<body>
<script>
fetch(
"https://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json"
)
.then((res) => {
console.log(res);
return res.json();
})
.then((data) => console.log(data.dataseries));
</script>
</body>
</html>
fetch()를 사용하여 JSON 형식의 날씨 정보 URL에서 데이터를 가져온 다음, json() 메서드를 사용하여 해당 데이터를 JavaScript 객체로 변환하여 처리한 코드json()json()임에도 불구하고, 결과는 JSON이 아니라 JSON을 입력으로 사용하여 파싱한 JavaScript 객체fetch()fetch() 통해 서버로부터 데이터를 클라이언트에 제공한다.fetch() 통해 웹 request를 보내고 response 객체를 얻는다.fetch()를 사용하여 웹 서버에서 데이터를 가져온 다음, json() 메서드를 사용하여 해당 데이터를 JavaScript 객체로 변환하여 처리<!DOCTYPE html>
<html>
<body>
<article></article>
<input
type="button"
value="fetch"
onclick="
// Asynchronous
fetch('JavaScript2').then((res) => {
console.log(res.status)
if (res.status === 404) {
alert('Not found')
}
}) // 파일의 데이터를 서버로부터 요청
console.log(1);
console.log(2);
"
/>
</body>
</html>
<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 src="fetchPage.js"></script>
</body>
function fetchPage(name) {
fetch(name) //
.then((res) => res.text()) //
.then((text) => (document.querySelector("article").innerHTML = text));
}