AJAX(Asynchronous JavaScript And XML)는 웹 페이지를 새로고침하지 않고도 서버와 데이터를 주고받을 수 있는 기술이다.
jQuery에서는 AJAX 요청을 쉽게 다룰 수 있도록 $.ajax(), $.get(), $.post() 등의 메소드를 제공한다.
✅ 비동기(Asynchronous) 통신
✅ 새로고침 없이 데이터 요청 및 응답 처리
✅ JSON, XML 등 다양한 데이터 포맷 지원
✅ 사용자 경험(UX) 향상
기본 문법
$.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); // 실패 시 실행될 함수
}
});
✅ 서버에서 데이터를 가져오거나, 데이터를 저장할 때 사용됨
예제: 버튼 클릭 시 서버에서 데이터 가져오기
<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" 출력됨
예제: 입력 폼에서 데이터를 서버로 전송
<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 방식은 데이터를 서버에 저장할 때 사용됨
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" })를 간략하게 줄인 형태
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);
}
});
서버에서 JSON 데이터 받아오기
$.ajax({
url: "/api/user",
method: "GET",
dataType: "json",
success: function(response) {
console.log("이름:", response.name);
console.log("나이:", response.age);
에러 처리 예제
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("서버 요청 중 오류가 발생했습니다.");
}
});
xhr은 XMLHttpRequest 객체로, AJAX 요처이 발생할 때 jQuery가 자동으로 전달하는 객체이다.
| 속성 | 설명 |
|---|---|
| xhr.status | HTTP 응답 상태 코드(예; 404, 500, 200 등) |
| xhr.statusText | 상태 메시지 (예: "Not Found", "Internal Server Error") |
| xhr.responseText | 서버에서 반환한 응답 데이터 (텍스트 형식) |
| xhr.getAllResponseHeaders() | 서버에서 보낸 모든헤더 정보 |