JavaScript의 3번째 AJAX에 대한 정리
Asynchronous Javascript And XML
즉, 비동기적인 방식으로 서버와 통신하는 방식이다.
프레임워크나 언어가 아닌 구현하는 방식이라는 점
웹 화면에서 화면을 갱신하지 않고 데이터를 서버로부터 가져와 처리하는 방법.
즉, 새로고침을 하지 않아도 됨.
일반적인 요청이 오면, 서버는 page를 만들어서 응답한다. 즉, 새로운 페이지로 응답하며 사용자는 화면 전환이 일어나는 새로운 페이지를 보게 된다.
하지만, AJAX로 요청하면 데이터만 받아오기 때문에 기존 페이지에 값만 추가하여 화면 전환이 일어나지 않는다.
XMLHttpRequest
이용<script>
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
console.log(ajax.responseText);
console.log(ajax.responseXML);
}
}
};
ajax.open("GET/POST", "호출 URL", true); // 1. get 또는 post 방식, 2. 호출할 url, 3. 비동기인가
ajax.send();
</script>
XMLHttpRequest
객체는 직접 구현해야 함.
fetch()
이용<script>
fetch("URL 링크") // 지정된 URL로 fetch 요청을 보냅니다.
.then(response => { // 요청이 성공하면 실행되는 then 메소드
if (!response.ok) { // 응답 상태가 정상이 아니면 (400 또는 500 에러)
throw new Error("400 또는 500 에러 발생!!!"); // 에러를 발생시킵니다.
}
return response.json(); // 응답 데이터를 JSON 형식으로 파싱하여 반환합니다.
})
.then(result => { // JSON 데이터를 받아 처리하는 then 메소드
console.log(result); // 결과를 콘솔에 출력합니다.
})
.catch(() => { // 에러 발생 시 실행되는 catch 메소드
console.log("에러 발생!!!");
});
</script>
XMLHttpRequest 객체는 Ajax ㅌ오신 시 전송방식, 경로, 서버로 전송할 data등 전송 정보를 담는 역할을 한다.
직접 Javascript로 Ajax를 프로그래밍 할 경우 브라우저 별로 통신 방식이 다르다.
하지만, 요즘의 웬만한 브라우저는 window.XMLHttpRequest로 통일할 수 있다.
function getXMLHttpRequest(){
if(window.ActiveXObject){
try{
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e1){
try{
return new ActiveXObject("Microsoft.XMLHTTP");
}catch(e2){
return null;
}
}
}else if(window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
return null;
}
}
var httpRequest = null;
function sendRequest(url, params, callback, method){
httpRequest = getXMLHttpRequest();
var httpMethod = method ? method : 'GET';
if(httpMethod != 'GET' && httpMethod != 'POST'){
httpMethod = 'GET';
}
var httpParams = (params == null || params == '') ? null : params;
var httpUrl = url;
if(httpMethod == 'GET' && httpParams != null){
httpUrl = httpUrl + "?" + httpParams;
}
//alert("method == " + httpMethod + "\turl == " + httpUrl + "\tparam == " + httpParams);
httpRequest.open(httpMethod, httpUrl, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.onreadystatechange = callback;
//alert(httpMethod == 'POST' ? httpParams : null);
httpRequest.send(httpMethod == 'POST' ? httpParams : null);
}
jQuery와 axios등과 같은 라이브러리 없이 브라우저 에서 지원하는 fetch() 함수로 구현이 가능해 졌다.
let promise = fetch(url, [options]);
// let promise = fetch(url, {method : "DELETE"})
<script>
let response = await fetch(url);
if(response.ok) {
let json = await response.json();
} else {
alert("에러 발생 : " + response.status)
}
</script>