Ajax : Asynchronous Javascript and Xml의 약자 브라우저가 가지고 있는 XMLHttpRequest 객체를 이용해서 전체 페이지를 새로 고치지 않고 페이지의 일부만을 로드하는 기법 비동기 통신이며, 클라이언트와 서버간에 XML, JSON, HTML, TEXT 등의 데이터를 주고받는 기술이다.
비동기 방식은 웹페이지를 로딩을 다시 하지 않고 데이터를 불러온다. Ajax를 통해 서버에 요청을 하더라도, 멈춰있지 않고 해당 프로그램은 계속 돌아가고 있다!! 시간이 빠르다는 장점과 전체를 갖고오지 않고 일부만 데이터를 갖고 올 수 있다는 장점을 가지고 있다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
window.onload = function() {
document.getElementById("btnOk1").onclick = function () {
sijak();
}
document.querySelector("#btnOk2").onclick = sijakXML;
let xhr;
function sijak() {
//alert("a"); // 부분데이터 : csv, json, xlm, txt~~
// Ajax : 비동기 방식으로 웹서버와 js 객체 간의 통신. 웹서버로부터 부분 데이터를 수신할 수 있다!!!
xhr=new XMLHttpRequest(); // 비동기 방식 처리 클래스
//alert(xhr);
//xhr.open("요청 방식","요청 파일명", true); // true : 비동기 방식 ,,,, false : 동기 방식
//let fname="js20.txt"
let fname="js20csv.txt"
xhr.open("get", fname, true);
xhr.onreadystatechange = function() {
//alert(xhr.readyState); // readyState가 4여야 일이 정상적으로 처리됬는지 알 수 있음
/*
readyState 속성값
0: 초기화이전(uninitialized) - 객체 생성만 되고 초기화 이전, 즉, open 수행전
1: 로딩중(loading) - 객체 생성 및 초기화, 그러나 send 수행전
2: 로딩완료(loaded) - send 수행 되었으나 헤더와 status 값 미도착
3: 서버 처리중(interactive) - 데이터 일부만 도착
4: 처리완료(completed) - 데이터 전부 도착
status 속성값
200: 성공 (OK)
403: 접근거부 (Forbidden)
404: 파일 없음 (Not Found)
500: 서버 내부 오류 (Internal Server Error)
*/
if(xhr.readyState == 4){ // 통신 상태 양호
//alert(xhr.status);
if(xhr.status == 200){ // 요청 성공
processFunction(); // callback함수
}
}
}
xhr.send(null); // get방식일때 null이라고 쓰기
}
function processFunction() {
let data = xhr.responseText; // xhr을 문자열로 받음==>responseText
//document.querySelector("#disp").innerText=data;
//let my=document.createTextNode(data);
//document.querySelector("#disp").appendChild(my);
// 행은 엔터로 구분
let rowData = data.split(String.fromCharCode(13)); // 아스키코드 13:cr
//alert(rowData.length);
let str = "";
for(let i = 0; i < rowData.length; i++){
let colData = rowData[i].split(",");
for(let j=0; j<colData.length; j++){
str += colData[j]; + " ";
}
str+="<hr>";
}
document.querySelector("#disp").innerHTML=str;
}
function sijakXML() {
xhr=new XMLHttpRequest();
xhr.open("get", "js20.xml", true)
xhr.onreadystatechange = function() {
if(xhr.readyState === 4){
if(xhr.status === 200) {
processXML();
}
}
}
xhr.send(null);
}
function processXML() {
// let data = xhr.responseText; // XML문서는 responseText를 읽으면 객체로 인정하지 않기 때문에 DOM 사용 불가
let data = xhr.responseXML; // XML 객체 읽기
//alert(data);
let sangpumItem = data.getElementsByTagName("sangpum");
//alert(sangpumItem.length);
let codeItem = data.getElementsByTagName("code");
let sangItem = data.getElementsByTagName("sang");
let str = "";
for(let i=0; i < sangpumItem.length; i++){
str += codeItem[i].childNodes[0].nodeValue + " ";
str += sangItem[i].firstChild.nodeValue + " ";
str += codeItem[i].getAttribute("price");
str += "<br>";
}
document.querySelector("#disp").innerHTML=str; // 덮어쓰기 함,,, appencChild면 추가로 쓰기
}
</script>
</head>
<body>
<h2>**Ajax 처리**</h2>
<button id="btnOk1">Ajax 원리 이해1</button><br>
<button id="btnOk2">XML 읽기</button><br>
<hr>
<div id="disp"></div>
</body>
</html>
위 코드를 통해 xml 데이터를 읽어오면
다음과 같은 결과를 얻을 수 있다.