본문 바로가기

Ajax

Ajax - (4) JSON 파일 읽어서 웹 브라우저에 출력하는 Ajax 예제

HTML

<!DOCTYPE html>
<html lang="ko" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Ajax 실습 - 2019.09.27</title>
    <style>
    body {background:#000; color:#fff;}
    </style>
    <script type="text/javascript">
      var xhttp;

      function createHttpRequest(){
        xhttp = new XMLHttpRequest();
      }

      function mySend(){
        createHttpRequest();
        xhttp.onreadystatechange = callFunction;
        xhttp.open("GET", "json.json", true);
        xhttp.send(null);
      }

      function callFunction(){
        if(xhttp.readyState == 4) {
          if(xhttp.status == 200){
            var responseData = xhttp.responseText;
            var jsonObject = eval('(' + responseData + ')');
            var name = jsonObject.username;
            var age = jsonObject.age;
            var address = jsonObject.address;
            document.getElementById("result").innerHTML = name + "\t" + age + "\t" + address;
          }
        }
      }
    </script>
  </head>
  <body>
    JSON 텍스트 파일 실습입니다.<br>
    <button type="button" onclick="mySend()" >파일수신</button>
    <div id="result"></div>
  </body>
</html>

JSON

{
  "username" : "홍길동",
  "age" : 20,
  "address" : "서울"
}

설명

ajax json 실습 예제

16~21번라인 : createcreateHttpRequest(); 함수를 호출하여 XMlXMLHttpRequest 객체를 새엉하고 GET 방식으로 서버에 json파일을 비동기로 요청합니다. 서버의 응답 처리를 위해서 onreadystatechange 프로퍼티에서는 readyState 반환값에 따라서 자동으로 호출하는 callFunction 함수를 설정합니다.

 

26번 라인 : JSON 데이터를 응답 받기 위해서 responseText 프로퍼티를 사용합니다.

 

27번 라인 : eval 함수를 이용하여 응답 데이터인 텍스트를 JSON 객체로 변환합니다.

 

 

728x90
300x250