AJAX-배우목록 가져오기

임재헌·2023년 4월 3일
0

AJAX

목록 보기
6/10
ACTORS.JSON
[
    {"name":"송강호","height":180,"weight":70}
   ,{"name":"정우성","height":185,"weight":75}
   ,{"name":"이정재","height":177,"weight":85}
]
<!DOCTYPE html>   
<html lang="ko"> 
<head>
    <meta charset="UTF-8">
<title>06_배우목록 </title> 
<style>
    #loader{
        width: 100%;
        height: 100%;
        background-color: cornsilk;
        position: fixed;
        left: 0;
        top: 0;
        background-image: url(loader.gif);
        background-repeat: no-repeat;
        background-position: center;
        display: none;
}
</style>
<!-- jquery import -->
<script src="jquery-3.6.4.min.js"></script>  
</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>
<script>
$("button").click(function(){
    //alert();
    // loader 이미지 보여줌
    $("#loader").show();
    //서버에 요청해서 응답 메세지 받아오기
    $.ajax("actors.json",{
        dataType:"json",
        error: function(error){
            alert(error);
        },
        success: function(result){
            //alert(result);

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

            //table의 tbody값 수정
            $(result).each(function(){
                //alert(this.name);
                //alert(this.height);
                //alert(this.weight);

                //$("<tr>") 요소생성
                //$("tr") 요소선택
                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");
            });
            //로딩되고 있는 이미지를 서서히 숨김
            $("#loader").fadeOut(1000);
        }
    });
});


</script>
</body>
</html>

0개의 댓글