본문 바로가기
Language/Javascript

[Javascript] Ajax 기본 정리

by SooooooooS 2023. 2. 14.
728x90

1.  Ajax 기본 골격

$.ajax({
  type: "타입",
  url: "URL",
  data: {},
  success: function(response){
    실행할 내용
  }
})
표현 설명
type GET, POST 둘 중 하나의 방식으로 요청
url 요청할 API URL 입력
data 요청하면서 줄 데이터(GET 요청시에는 비워둔다.)
success 성공하면 서버에서 준 응답결과를 response담고 활용한다.

2. Type

  • GET
    • 일반적으로 Read 할때 사용
    • URL 뒤에 ? 를 붙여 key=value로 전달
  • POST
    • 일반적으로 Create, Update, Delete 할때 사용

3. 기본 코드

<!doctype html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title> test </title>

    <!-- jQuery를 import, 이를 해줘야 ajax 실행 가능 -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <style type="text/css">
        div {
            margin: 10px 0 20px 0;
        }
    </style>

    <script>
        function q1() {
            <!-- ajax 부분 -->
            $.ajax({
                type: "요청할 타입",
                url: "URL",
                data: {},
                success: function (response) {
                    실행할 내용
                }
            })
        }
    </script>
</head>

<body>
    <div>
        <button onclick="q1()">버튼1</button>
    </div>
</body>
</html>
728x90