1. Ajax란?
비동기 자바스크립트와 XML의 합성어(Asynchronous JavaScript And XML)
→ AJAX의 강력한 특징은 페이지 전체를 리프레쉬 하지 않고서도 수행 되는 '비동기성'
2. Ajax 예제(비동기 처리)
- test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>핫하</h2>
</body>
</html>
- ajax.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<button id="ajaxButton" type="button">Make a request</button>
<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
if(!httpRequest) {
alert('XMLHTTP 인스턴스를 만들 수가 없어요 ㅠㅠ');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'test.html');
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
document.body.innerHTML += httpRequest.responseText;
} else {
alert('request에 뭔가 문제가 있어요.');
}
}
}
})();
</script>
</body>
</html>
3. jQuery로 Ajax 사용하기
- ajax2.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<button id="ajaxButton" type="button">get</button>
<script>
$("#ajaxButton").click(function() {
$.ajax("test.html").done(function(data) {
alert(data);
$("body").append(data);
}).fail(function() {
alert('request에 뭔가 문제가 있어요.')
})
});
</script>
</body>
</html>