본문 바로가기
Programming/HTML & CSS & JavaScript

jQuery 2일차(2) - 이벤트, Ajax

by yoon9i 2024. 5. 20.

####################################################################
11. Event
https://api.jquery.com/category/events/

1> 이벤트 설정 및 해제

    .on("이벤트타입1 이벤트타입2"[,"selector",data], function(){});
    .off("이벤트타입",[,"selector",function(){}]);
    .one("이벤트타입1 이벤트타입2"[,data],function(){});

==> 이벤트핸들러(함수) 에서 this 는 이벤트소스를 참조한다.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>jQuery08_이벤트</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>

        $(document).ready(function () {
            // https://api.jquery.com/category/events/

            // 버튼이벤트처리
            // .on("이벤트타입1 이벤트타입2"[,"selector",data], function(){});
            $("#xxx").on("click mouseover", function () {
                console.log("ok", this); // this 는 이벤트 소스이고 JS 객체이다.

                // OK 얻기
                // console.log($("xxx").text());
                console.log($(this).text());
            });

            // event 객체 사용해서 form 의 자동 서브밋 방지하기
            $("#myForm").on("submit", function () {
                // alert("submit");

                var id = $("#userid").val();
                if (id.length == 0) {

                    event.preventDefault();
                    alert("id값 필수")
                }
            });



        });
    </script>
</head>

<body>
    <button id="xxx">OK</button>

    <form action="target.html" id="myForm">
        userid: <input type="text" name="userid" id="userid"><br>
        passwd: <input type="text" name="passwd" id="passwd"><br>
        <input type="submit" value="로그인">
    </form>
</body>

</html>



2> trigger() 메서드
기능:
    <button>ok</button>
    <button>cancel</button>

    ==> ok 를 버튼을 누르면 cancel 버튼이 실행된다???

<!DOCTYPE html>
<html lang="en">

<head>
    <title>jQuery08_이벤트2_trigger</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>

        $(document).ready(function () {
            // https://api.jquery.com/category/events/

            $("#xxx").on("click", function () {
                $("#yyy").trigger("click");
            });
            $("#yyy").on("click", function () {
                console.log("cancel");
            });
        });
    </script>
</head>

<body>
    <button id="xxx">OK</button>
    <button id="yyy">CANCEL</button>
</body>

</html>

 

####################################################################
12. ajax
https://api.jquery.com/jQuery.ajax/

$.ajax(url[,settings]);
$.ajax([settings]);

==> 위의 settings 는 JSON 포맷을 가짐.

1> GET 방식

<!DOCTYPE html>
<html lang="en">

<head>
    <title>jQuery09_Ajax1_GET방식</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>

        $(document).ready(function () {
            // https://api.jquery.com/jQuery.ajax/

            // JS 용 Ajax-GET 요청
            $("#xxx").on("click", function () {
                var url = "https://reqres.in/api/users/2";
                var req = async function () {

                    await fetch(url)
                        // url 의 응답을 json 형태로 return
                        .then(response => response.json())
                        // json 형태로 받고 {} 안에 작업
                        .then(json => {
                            var person = json.data;
                            console.log(person);
                        })
                        .catch(() => console.log("error발생"))
                        .finally(() => console.log("finally 발생"));

                };
                req(); // 호출

            });

            // jQuery 용 Ajax-GET 요청
            $("#yyy").on("click", function () {

                $.ajax({
                    method: "get",
                    url: "https://reqres.in/api/users/2",
                    dataType: 'json', // "json" or "text"
                    success: function (data, status, xhr) {
                        // data : jsondata
                        console.log("data: ", data, data.data);
                        console.log("status: ", status);
                    },
                    error: function (xhr, status, error) {
                        console.log("error: ", error);
                    }
                });
            });
        });
    </script>
</head>

<body>
    <button id="xxx">JS용 Ajax-GET요청</button>
    <button id="yyy">jQuery용 Ajax-GET요청</button>
    <div id="result"></div>
</body>

</html>


2> POST 방식

타켓: https://reqres.in/api/users
method: post
전달 데이터: 
            {
                "name": "morpheus",
                "job": "leader"
            }

응답데이터:
            {
                "name": "morpheus",
                "job": "leader",
                "id": "295",
                "createdAt": "2024-05-17T07:24:36.253Z"
            }

새로운 값을 생성하고 성공했을 때: 201

<!DOCTYPE html>
<html lang="en">

<head>
    <title>jQuery09_Ajax2_POST방식</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>

        $(document).ready(function () {
            // https://api.jquery.com/jQuery.ajax/

            // JS 용 Ajax-POST 요청
            $("#xxx").on("click", function () {
                var url = "https://reqres.in/api/users";
                var req = async function () {

                    await fetch(url, {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                            // 'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        // body의 데이터 유형은 반드시 "Content-Type" 헤더와 일치해야 함
                        body: JSON.stringify({
                            // "name": "morpheus",
                            "name": "홍길동",
                            "job": "leader"
                        }),
                    })
                        // url 의 응답을 json 형태로 return
                        .then(response => response.json())
                        // json 형태로 받고 {} 안에 작업
                        .then(json => {
                            console.log(json);
                        })
                        .catch(() => console.log("error발생"))
                        .finally(() => console.log("finally 발생"));

                };
                req(); // 호출

            });

            // jQuery 용 Ajax-POST 요청
            $("#yyy").on("click", function () {

                $.ajax({
                    method: "POST",
                    url: "https://reqres.in/api/users",
                    dataType: 'json', // "json" or "text"
                    contentType: "application/json",
                    data: JSON.stringify({
                        // "name": "morpheus",
                        "name": "홍길동",
                        "job": "leader"
                    }),
                    success: function (data, status, xhr) {
                        // data : jsondata
                        console.log("data: ", data);
                        console.log("status: ", status);
                    },
                    error: function (xhr, status, error) {
                        console.log("error: ", error);
                    }
                });
            });
        });
    </script>
</head>

<body>
    <button id="xxx">JS용 Ajax-POST요청</button>
    <button id="yyy">jQuery용 Ajax-POST요청</button>
    <div id="result"></div>
</body>

</html>