AJAX 테이블 연습

Jane·2023년 3월 20일
0

IT 수업 정리

목록 보기
77/124

ajax 초기 설정

$.ajax({객체 내용});

  • type : GET 방식? METHOD 방식?
  • url : json 파일의 주소
  • success : function(result){} 안에 내용을 적는다.
    • console.log(result)로 디버깅

테이블 만들기

<body>
    <table id="list-table" width="500" border="1"></table>
</body>
  • html body 태그 안에 table을 넣는다.

1번 > html 내용을 적으면서 append

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script>
        $(function () {
            $.ajax({
                type: "GET",
                url: "http://sample.bmaster.kro.kr/contacts?pageno=3&pagesize=10",
                success: function (result) {
                    console.log(result);

                    var htmls = "";
                    $("#list-table").html("");

                    $("<tr>", {
                        html: "<td>" + "번호" + "</td>" +  // 컬럼명들
                            "<td>" + "이름" + "</td>" +
                            "<td>" + "전화번호" + "</td>" +
                            "<td>" + "주소" + "</td>" +
                            "<td>" + "사진" + "</td>" +
                            "<td>" + "삭제" + "</td>"
                    }).appendTo("#list-table")

                    $(result.contacts).each(function () {

                        htmls += '<tr>';
                        htmls += '<td>' + this.no + '</td>';
                        htmls += '<td>' + this.name + '</td>';
                        htmls += '<td>' + this.tel + '</td>';
                        htmls += '<td>' + this.address + '</td>';
                        htmls += '<td>' + '<img src=' + this.photo + ' />' + '</td>';
                        htmls += '<td>' + "<input type='button' class='del-button' id=" + this.no + ' value="삭제" />' + '</td>';
                        htmls += '</tr>';
                    });

                    $("#list-table").append(htmls);

                }
            });
        });

    </script>
  • 객체마다 하나씩 배열로 돌려서 html이란 변수(var)에 담고, 변수를 table에 append하는 방식

삭제 버튼이 작동하도록 하게 하기

    <script>
        $(document).on("click", ".del-button", function () {
            console.log(this);
            $(this).parent().parent().remove();
        }); // tr > td > input(.del_button)
    </script>
  • 기존에 있는 스크립트와 별개의 스크립트로 또 만들어서 실행할 수 있다.
  • ".del-button"을 클릭했을 때 동적 처리가 가능하도록 한다.

원래의 형태

<tr>
<td>1601087500172</td>
<td>Keandra Russell</td>
<td>010-3456-8299</td>
<td>서울시</td>
<td><img src="http://sample.bmaster.kro.kr/photos/100.jpg"></td>
<td><input type="button" class="del-button" id="1601087500172" value="삭제"></td>
</tr>
  • 세분화된 html 코드를 하나하나 script에 적용하는 형식으로 바꿔가면서 작업한다.

2번 > jQuery 문법으로 바꿔서 작업

success: function (result) {

                    console.log(result);

                    $("#list-table").append(
                        $("<tr></tr>")
                            .append($("<td></td>").text("번호"))
                            .append($("<td></td>").text("이름"))
                            .append($("<td></td>").text("전화번호"))
                            .append($("<td></td>").text("주소"))
                            .append($("<td></td>").text("사진"))
                            .append($("<td></td>").text("삭제"))
                    );

                    $(result.contacts).each(function () {
                        $("#list-table").append(
                            $("<tr></tr>")
                                .append($("<td></td>").text(this.no))
                                .append($("<td></td>").text(this.name))
                                .append($("<td></td>").text(this.tel))
                                .append($("<td></td>").text(this.address))
                                .append($("<td></td>").append($("<img></img>").attr("src", this.photo)))
                                .append($("<td></td>").append($("<input></input>").attr("id", this.no).attr("type", "button").attr("class", "del-button").attr("value", "삭제")))
                        );
                    });
                }

3번 > 테이블을 숨기고 내용물을 clone()해서 만들기

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="/js/board.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "http://sample.bmaster.kro.kr/contacts?pageno=3&pagesize=10",
                success: function (result) {
                    console.log(result);

                    $("#list-table").hide();

                    $(result.contacts).each(function () {
                        var tr = $("#tr-copy").clone();

                        //찾는법 $(".dname td:nth-child(2)").text();
                        //$(".dname").find("td:eq(1)").text()
                        tr.find("td:eq(0)").text(this.no);
                        tr.find("td:eq(1)").text(this.name);
                        tr.find("td:eq(2)").text(this.tel);
                        tr.find("td:eq(3)").text(this.address);
                        tr.find("td:eq(4)").children("img").attr("src", this.photo);

                        $("#list-table").append(tr);
                    });

                    $("#list-table").find("tr:eq(1)").remove();

                    $("#list-table").show();
                },
                error: function (e) {
                    console.log(e);
                },
            });
        });
    </script>
    <script>
        $(document).on("click", ".del-button", function () {
            console.log(this);
            $(this).parent().parent().remove();
        });
    </script>
</head>

<body>
    <table id="list-table" width="500" border="1">
        <tr>
            <td>번호</td>
            <td>이름</td>
            <td>전화번호</td>
            <td>주소</td>
            <td>사진</td>
            <td>삭제</td>
        </tr>
        <tr id="tr-copy">
            <td>1678846480504</td>
            <td>문세홍</td>
            <td>010-1111-9999</td>
            <td>Seoul</td>
            <td><img src="http://sample.bmaster.kro.kr/photos/noimage.jpg" /></td>
            <td>
                <input id="1678846480504" type="button" class="del-button" value="삭제" />
            </td>
        </tr>
    </table>
</body>

</html>
  • 임시로 형태를 만들어놓고, 복사해가면서 새로운 것으로 바꿔넣는다.
profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글