티스토리 뷰
Asynchronous JavaScript And XML의 약자로 웹 서버에 접속하는 기법 중 하나이다. XMLHttpRequest를 통해 서버로부터 데이터를 요청하게 된다. 사용자 쪽에서 로딩하는 모습이 보이지 않고, 뒷단에 접속해서 data를 가져오는 방법이다. 페이지 소스에서도 내용이 노출되지 않는다는 장점이 있다.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
여기서 ajax_info.txt는 웹 서버에서 불러들일 내용이 있는 파일이다. 이 파일의 내용은 소스코드에서 볼 수 없다. ajax_info.txt 파일 앞에 "./" 같은 경로 설정이 없는 것은 이 파일이 현재 HTML 파일과 동일한 디렉터리에 있다는 뜻이다.
XMLHttpRequest
(사용자에게 보이지 않는) 뒷단에서 데이터를 받아올 때 사용한다. 웹 페이지 전체를 로딩할 필요없이 데이터를 받아오는 것(또는 데이터를 업데이트 하는 것)이 가능하다는 것이다.
서버와 데이터를 교환할때 XMLHttpRequest Object를 사용한다.
XMLHttpRequest Object을 생성하는 방법:
var xhttp = new XMLHttpRequest();
XMLHttpRequest Object Properties
- onreadystatechange: readyState 속성이 변할 때 호출할 함수를 정의한다
- readyState
0 | request not initialized |
1 | server connection established |
2 | request received |
3 | processing request |
4 | request finished and response is ready |
- responseText: response data를 string으로 리턴해준다
- responseXML: response data를 XML data로 리턴해준다
- status
200 | OK |
403 | Forbidden |
404 | Not Found |
- statusText: 위의 상태를 텍스트로 리턴해준다
readyState가 4이고, status가 200때 요청이 준비된 상태를 의미한다.
서버에 요청 보내기
xtthp. | open( | "GET", | "ajax_info.txt", | true | ); |
어떤 요청을 보낼것인지를 명시한다. | GET 또는 POST |
서버 파일 위치 .txt .xml .asp .php 파일 모두 가능하다 |
서버 요청이 asynchronously 처리되록 해준다 (화면이 새로고침 될 필요 없이 데이터가 로딩 된다) |
- xttp.open(method, url, async)
- send() : GET 사용할 때
- send(string): POST 사용할 때
Asynchronous(비동기적) vs Synchronous(동기적)
- 동기적: 수신을 다 받을때까지 기다린 후 작업을 하는 것
- 비동기적: 수신을 다 받아오지 않아도(수신 상관없이) 작업을 이어나가는 것
- 사용 예시) 네이버에서 검색할 때 실시간 검색순위는 알아서 백그라운드에서 실행되고 나는 내가 하고 싶은 작업들을 하면 된다.
Callback function
Server Response Properties
- responseText: string으로 데이터 요청을 받아온다
- 예시) xhttp.open("GET", "ajax_info.txt", true);
document.getElementById("demo").innerHTML =
this.responseText;
}
- responseXML: XML 데이터로 요청을 받아온다
- 예시) xhttp.open("GET", "cd_catalog.xml", true);
function() {
if (this.readyState == 4 && this.status == 200) {
xmlDoc = this.responseXML; // XML문서의 데이터를 받아온다
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt = txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
};
Server Response Methods
- getResponseHeader(): 어떤 특정 header information을 리턴해준다
- 예) this.getResponseHeader('Last-Modified')
- getAllResponseHeaders(): header에 있는 모든 정보를 리턴해준다
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
</script>
XML 파일
XML 파일 형식: XML 문서를 반드시 맨 처음에 선언해야 한다
<?xml version="1.0" encoding="UTF-8" ?>
그 이후의 element는 <tag>내용</tag> 형식으로 되어 있다
<?xml version="1.0" encoding="UTF-8" ?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
</CATALOG>
XML 파일의 내용을 읽어들이는 방법 (passing 하는 법)
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>"; //table의 제일 윗상단을 만든다
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) { //각 행의 내용을 채운다
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
XML 문서에서 특정 element 읽어오는 방법
displayCD(i) 함수에 index 파라미터를 주어서 원하는 element를 읽어오게 한다.
<!DOCTYPE html>
<html>
<body>
<div id='showCD'></div>
<script>
displayCD(0); //displayCD() 함수에 주는 파라미터 값의 index element를 불러온다
function displayCD(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("CD");
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
</script>
</body>
</html>
Navigate XML nodes
<!DOCTYPE html>
<html>
<body>
<div id='showCD'></div><br>
<input type="button" onclick="previous()" value="<<">
<input type="button" onclick="next()" value=">>">
<script>
var i = 0, len;
displayCD(i);
function displayCD(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("CD");
len = x.length;
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
function next() {
if (i < len-1) {
i++;
displayCD(i);
}
}
function previous() {
if (i > 0) {
i--;
displayCD(i);
}
}
</script>
</body>
</html>
Show information when element(data brought from XML)is clicked
-a simple CD catalog application
Table에 있는 각 항목을 만들때 맨 앞에 table += "<tr onclick='displayCD(" + i + ")'><td>"; 부분을 덧붙여서 클릭할 때마다 윗 상단에 각 행에 대한 정보가 나타날 수 있도록 한다. displayCD 라는 함수는 따로 정의해놓는다.
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<p>Click on a CD to display album information.</p>
<p id='showCD'></p>
<table id="demo"></table>
<script>
var x,xmlhttp,xmlDoc
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "cd_catalog.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("CD");
table="<tr><th>Artist</th><th>Title</th></tr>";
for (i = 0; i <x.length; i++) {
table += "<tr onclick='displayCD(" + i + ")'><td>";
table += x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue;
table += "</td><td>";
table += x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue;
table += "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
function displayCD(i) {
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
</script>
</body>
</html>
AJAX PHP
- showHint: 자동 완성 기능처럼 hint를 주는 기능
- onkeyup: 키보드에 있는 자판을 하나씩 누를 때 마다 envent로 인식한다.
- .php?q= 형식으로 되어 있어야 사용자가 입력하는 텍스트가 실시간으로 검색된다. (실수하지 않도록 주의 할 것!)
<!DOCTYPE html>
<html>
<body>
<h3>Start typing a name in the input field below:</h3>
<p>Suggestions: <span id="txtHint"></span></p>
<p>First name: <input type="text" id="txt1" onkeyup="showHint(this.value)"></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET", "gethint.php?q="+str, true);
xhttp.send();
}
</script>
</body>
</html>
위의 예제에서 GET 방식을 이용하기 때문에 url에 사용자가 input text상자에 입력한 값이 그대로 나타날 것임을 알 수 있다. 요청을 할때 받아올 페이지도 살펴보면 .php?q= + str 사용자가 입력한 text 내용을 뒤에다 이어 붙여서 계속해서 요청을 보낸다는 것을 알 수 있다.
AJAX ASP
파일만 asp파일로 해서 위와 동일한 작업을 할 수 있다.
다만 닷홈 호스팅 환경은 APM(apache + php + mySql) 환경이기 때문에 닷홈 호스팅에서는 작동하지 않는다. (asp는 Microsoft사에서 만든 스크립트 엔진이다)
xmlhttp.open("GET", "gethint.asp?q=" + str, true);
AJAX Database
- showCustomer(): database로부터 데이터를 가져와서 사용자에게 보여주게 된다
- onchange 이벤트
PHP와에서 마찬가지로 GET 방식을 이용하기 때문에 url에 사용자가 input text상자에 입력한 값이 그대로 나타날 것임을 알 수 있다. 요청을 할때 받아올 페이지도 살펴보면 .php?q= + str 사용자가 입력한 text 내용을 뒤에다 이어 붙여서 계속해서 요청을 보낸다는 것을 알 수 있다.
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
'JavaScript' 카테고리의 다른 글
JavaScript BOM (0) | 2020.07.29 |
---|---|
JavaScript: Element의 동적 추가와 삭제 (0) | 2020.07.29 |
JavaScript HTML DOM: Event listener (1) | 2020.07.28 |
JavaScript forms (0) | 2020.07.28 |
Javascript: function, events (0) | 2020.07.27 |
- Total
- Today
- Yesterday
- jsp
- Block_element #inline_element
- css
- HTML #CSS
- JSP_CRUD
- meta #link #script #base #HTML
- HTML #id #iframe
- HTML_Formatting
- annotation
- DynamicWebProject
- UserBean
- javascript #datatype
- head #title #style
- html
- Mavenproject
- text_shadow
- box_model
- 2020Camp
- HTML_Forms
- HTML #Canvas #SVG
- STS4
- JSP환경구축
- links lists tables display
- DB4free
- HTML #Headings #Paragraph #Styles
- HTML #media #video #YouTube
- HTML #class
- 인용문 #주석
- HTML #Tables
- fontstyle
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |