웹개발 교육/Ajax

[45일] Ajax (4) - callback 함수

ewok 2022. 9. 29. 12:28

callback 함수를 통해 json 데이터를 받아오자

 

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>06_callback함수.html</title>
        <script src="jquery-3.6.1.min.js"></script>
    </head>  
    <body>

        <button>* JSON 데이터 받아오기 *</button>
        <div id="panel"></div>

        <script>
            $("button").click(function(){
                //$.getJSON(url, callbakck함수) JSON 데이터를 가져온다
                $.getJSON("sungjuks.json", responseProc);
            });//click end

            function responseProc(result, status, xhr){ //callback 함수
                // alert(result);
                // alert(status);
                // alert(xhr);
                let str = "<table border='1'>";
                $.each(result, function(idx, data){
                    // alert(idx);  //요소 순서
                    // alert(data); //각 배열 요소값
                    str += "<tr>";
                    str += "    <td>" + data.name + "</td>";
                    str += "    <td>" + data.id + "</td>";
                    str += "    <td>" + data.kor + "</td>";
                    str += "    <td>" + data.eng + "</td>";
                    str += "    <td>" + data.mat + "</td>";
                    str += "</tr>";
                });//each() end
                str += "</table>";
                $("#panel").empty();
                $("#panel").append(str);
            }//responseProc() end
        </script>
        
    </body>
</html>

$.getJSON 함수에 매개변수로 함수를 사용하였다. 이것이 callback 함수이다. 앞서 했던 방식과는 달리 error 발생 시 동작하는 함수가 없기 때문에 json 파일명을 다르게 주는 등 에러가 발생해도 동작되는 것은 없다.

 

callback 함수에는 앞에서 성공 시 동작하는 함수와 동일하게 작성해주었다.

append 함수 위에 empty 함수를 작성했기 때문에 데이터가 쌓이지는 않는다.