[jQuery] AJAX와 서버 통신

젼이·2025년 2월 7일

jQuery 정복하기

목록 보기
3/6

1. AJAX란?

AJAX(Asynchronous JavaScript And XML)는 웹 페이지를 새로고침하지 않고도 서버와 데이터를 주고받을 수 있는 기술이다.
jQuery에서는 AJAX 요청을 쉽게 다룰 수 있도록 $.ajax(), $.get(), $.post() 등의 메소드를 제공한다.


✅ 비동기(Asynchronous) 통신
✅ 새로고침 없이 데이터 요청 및 응답 처리
✅ JSON, XML 등 다양한 데이터 포맷 지원
✅ 사용자 경험(UX) 향상



2. AJAX 기본 개념

기본 문법

$.ajax({
	url: "서버주소", // 요청을 보낼 서버 주소
    method: "GET", // HTTP 요청 방식 (GET, POST 등)
    data: { key: "value"}, // 서버로 보낼 데이터 (POST 요청 시 유용)
    dataType: "json", // 응답 데이터 타입 (json, xml, text 등)
    success: function(response) {
    	console.log(response); // 성공 시 실행될 함수
    },
    error: function(xhr, status, error) {
    	console.log("오류 발생:", error); // 실패 시 실행될 함수
    }
});

✅ 서버에서 데이터를 가져오거나, 데이터를 저장할 때 사용됨



3. AJAX를 사용한 GET 요청 (서버에서 데이터 가져오기)

예제: 버튼 클릭 시 서버에서 데이터 가져오기

<button id="myButton">데이터 가져오기</button>
<div id="result"></div>

<script>
  	$(document).ready(function() {
  		$("#myButton").on("click", function() {
  			$.ajax({
  				url: "/api/data",
  				method: "GET",
  				dataType: "json",
  				success: function(response) {
  					$("#result").text(response.data);
  				},
  				error.function() {
  					$("#result").text("데이터를 가져오는데 실패했습니다.");
  				}
  			});
  		});
  	});
</script>

✅ 버튼 클릭 시 서버에서 데이터를 받아와서 <div id="result">에 표시
✅ 서버 응답 데이터가 {"data":"Hello, world!"}라면 -> 화면에 "Hello, World" 출력됨




4. AJAX를 사용한 POST 요청 (서버로 데이터 전송)

예제: 입력 폼에서 데이터를 서버로 전송

<input type="text" id="name" placeholder="이름 입력">
<button id="submitBtn">제출</button>
<p id="message"></p>

<script>
    $(document).ready(function() {
        $("#submitBtn").on("click", function() {
            var name = $("#name").val(); // 입력된 이름 가져오기

            $.ajax({
                url: "/api/submit", // 서버 주소
                method: "POST", // POST 요청
                data: { name: name }, // 보낼 데이터
                success: function(response) {
                    $("#message").text(response.message); // 응답 메시지 출력
                },
                error: function() {
                    $("#message").text("데이터 전송에 실패했습니다.");
                }
            });
        });
    });
</script>

✅ 서버로 데이터를 전송하고, 응답 데이터를 화면에 표시
✅ POST 방식은 데이터를 서버에 저장할 때 사용됨




5. jQuery에서 $.get()과 $.post()

jQuery에서는 AJAX 요청을 더욱 간편하게 작성할 수 있도록 $.get()과 $.post() 메서드를 제공한다.


GET 요청

$.get("/api/data", function(response) {
  	console.log(response); // 서버에서 받아온 데이터 출력
});

✅ 서버에서 데이터를 가져올 때 사용
✅ $.ajax({ method: "GET" })을 간략하게 줄인 형태


POST 요청

$.post("/api/submit", { name: "홍길동"}, function(response) {
  	console.log(response.message); // 서버 응답 출력
});

✅ 서버에 데이터를 보낼 때 사용
✅ $.ajax({ method: "POST" })를 간략하게 줄인 형태




6. AJAX 요청 시 JSON 데이터 주고받기

AJAX 요청에서 주로 JSON 데이터를 사용하며, 서버에서 JSON 응답을 받아 처리할 수 있다.


JSON 데이터를 서버에 보내기

$.ajax({
  	url: "/api/user",
  	method: "POST",
  	contentType: "application/json",
  	data: JSON.stringify({ name: "홍길동", age: 30 }),
  	success: function(response) {
      	console.log("응답:", response);
    }
});
  • contentType: "application/json" -> JSON 형식으로 전송
  • JSON.stringify({}) -> JavaScript 객체를 JSON 문자열로 변환

서버에서 JSON 데이터 받아오기

$.ajax({
  	url: "/api/user",
  	method: "GET",
  	dataType: "json",
  	success: function(response) {
      	console.log("이름:", response.name);
      	console.log("나이:", response.age);
  • 서버 응답이 { "name": "홍길동", "age": 30 }이면 정상적으로 출력됨

에러 처리 예제

AJAX 요청이 실패했을 때 적절한 에러 처리가 필요하다.

$.ajax({
    url: "/api/data",
    method: "GET",
    success: function(response) {
        console.log("데이터:", response);
    },
    error: function(xhr, status, error) {
        console.log("에러 상태:", status);
        console.log("에러 메시지:", error);
        alert("서버 요청 중 오류가 발생했습니다.");
    }
});
  • error 콜백 함수에서 에러 상태와 메시지를 출력
  • 서버 요청 실패 시 사용자에게 알림 표시



7. xhr란? (XMLHttpRequest 객체)

xhr은 XMLHttpRequest 객체로, AJAX 요처이 발생할 때 jQuery가 자동으로 전달하는 객체이다.

  • 서버와의 HTTP 요청과 응답을 관리하는 객체
  • 요청 상태, 응답 데이터, 헤더 정보 등을 포함
  • AJAX 요청이 실패했을 때 추가 정보를 얻을 수 있음.


xhr의 주요 속성

속성설명
xhr.statusHTTP 응답 상태 코드(예; 404, 500, 200 등)
xhr.statusText상태 메시지 (예: "Not Found", "Internal Server Error")
xhr.responseText서버에서 반환한 응답 데이터 (텍스트 형식)
xhr.getAllResponseHeaders()서버에서 보낸 모든헤더 정보
profile
신입 개발자 임니당 : > (2025.02.05~)

0개의 댓글