자바스크립트를 이용해서 내부적으로 통신할 수 있는 방법이다.


Ajax : Asynchronous JavaScript and XML -> 자바스크립트를 이용해서 비동기적으로 서버와 브라우저가 데이터를 주고 받는 방식을 의미


이 때 사용하는 API가 XMLHttpRequest이다. (IE5,6에서는 XMLHttpRequest 대신 ActiveXObject("Msxml2.XMLHTTP.6.0")을 사용해야 함)

꼭 XML을 사용해서 통신해야 하는 것은 아니다. XML보다 JSON을 더 많이 사용한다.



** Ajax를 실습해보기 위해서는 서버 환경이 구축돼있어야 한다.


demo1.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
</head>
<body>
<p>time : <span id="time"></span></p>
<input type="button" id="execute" value="execute" />
<script>
    document.querySelector('input').addEventListener('click'function(event){
        var xhr = new XMLHttpRequest();
        xhr.open('GET''time.jsp');
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                document.querySelector('#time').innerHTML = xhr.responseText;
            }
        }
        xhr.send();
    });
</script>
</body>
</html>
cs



time.php

1
2
3
4
5
<?php
    $d1 = new DateTime;
    $d1->setTimezone(new DateTimezone("asia/seoul"));
    echo $d1->format('H:i:s');
?>
cs



demo.html을 실행하고 개발자도구로 네트워크를 살펴보자

1. demo.html 실행



2. excute 클릭


php가 아닌 jsp로 만들어버려서 코드가 그대로 나온다. 여기서 살펴볼 것은 time 파일이 호출되는 것이다.

화면의 reload 없이 비동기적으로 데이터만 가져와 뿌려준다.

+ Recent posts