웹개발 교육/jQuery

[44일] jQuery (17) - Ajax

ewok 2022. 9. 28. 17:59

어떤 버튼을 누르면 로딩을 기다리는 동안 모래시계 등 이미지를 보여주는 경우가 있다.

그리고 서버에 요청해서 메시지를 받아 오는 경우도 있다.(댓글 더보기)

이러한 작업을 해보자

 

우선 받아올 메시지가 담겨있는 파일을 작성하자 (따로 요청할 서버가 현재 없으니 파일에서 가져온다.)

 

actors.json

[
   {"name":"송강호", "height":180, "weight":70}
  ,{"name":"정우성", "height":185, "weight":75}
  ,{"name":"이정재", "height":177, "weight":85}
]

 

16_ajax.html

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>16_ajax.html</title>
        <script src="jquery-3.6.1.min.js"></script>
        <style>
            #loader {
                width: 100%;
                height: 100%;
                background-color: #EDE9DF;
                position: fixed;
                left: 0;
                top: 0;
                background-image: url("loader.gif");
                background-repeat: no-repeat;
                background-position: center;
                /*1)CSS추가 : 처음에는 숨겼다가*/
                display: none;
            }
        </style>
    </head>  
    <body>

        <h3>배우 목록 보여주기</h3>

        <div id="loader"></div>

        <button>서버에게 요청!!</button>
        <hr>
        <table border="1">
            <thead>
                <tr>
                    <th>이름</th>
                    <th>키</th>
                    <th>몸무게</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td colspan="3">없습니다</td>
                </tr>
            </tbody>
        </table>
        
    </body>
</html>

 

여기에서 서버에게 요청!! 버튼을 클릭하면 로딩 이미지가 나오게 하자

<script>
    $("button").click(function(){
        //2)loader 이미지 보여줌
        $("#loader").show();  //.css("display","block") 와 동일

    });//click end
</script>

 

 

이번에는 서버에 요청해서 메시지를 받아오는 작업을 해보자

<script>
        //3)서버에 요청해서 응답 메시지 받아오기(댓글더보기 등)
        $.ajax("actors.json", {
            dataType:"json"
            ,error:function(error){
                alert(error);
            }
            ,success:function(result){
                //alert(result);

                //4)기존의 <tbody>값을 전부 지움
                $("tbody").empty();

                //5)table의 tbody값 수정
                $(result).each(function(){

                    let $tr = $("<tr>");
                    let $td1 = $("<td>").text(this.name);
                    let $td2 = $("<td>").text(this.height);
                    let $td3 = $("<td>").text(this.weight);

                    $tr.append($td1, $td2, $td3).appendTo("tbody");
                });//each() end

                //6)로딩되고 있는 이미지를 서서히 숨김
                $("#loader").fadeOut(1000);
            }//success end
        });//ajax() end
    });//click end
</script>

아직 ajax에 대해 다루지 않았지만 추후 알아보기로 하자

 

우선, actors.json 파일을 받아오는데 에러가 날 경우 실행되는 function과 성공할 경우 실행되는 function이 있다. 에러 발생 시 에러 메시지를 띄워주게 했다.

 

성공 시 '없습니다' 부분에 받아온 데이터를 입력해줘야 한다. 그것이 성공 시의 function이다. each 반복문으로 받아온 데이터를 요소 생성하여 tbody에 출력되게 했다.

 

또 로딩 이미지를 서서히 사라지면서 화면이 나타나게 했다.