jQuery Ajax
바닐라 자바스크립트로 Ajax를 수행하기 위해서 XMLHttpRequest 객체를 사용합니다.
jQuery에서는 Ajax와 관련된 메서드를 제공하므로 더 쉽게 Ajax 요청을 구현할 수 있습니다.
관련 메서드는 다음과 같습니다.
메서드 | 설명 |
$.ajax() | 범용적인 Ajax 관련 메서드 |
$.get() | get 방식으로 Ajax 수행 |
$.post() | post 방식으로 Ajax 수행 |
$.getJSON() | get 방식으로 Ajax를 수행해 JSON 데이터를 가져옴 |
$.getScript() | get 방식으로 Ajax를 수행해 Script 데이터를 가져옴 |
$(<선택자>).load() | Ajax를 수행하고 선택자로 선택한 문서 객체 안에 집어넣음 |
$(<선택자>).serialize() | 입력 양식의 내용을 요청 매개변수 문자열로 만듬 |
$(<선택자>).serializeArray() | 입력 양식의 내용을 객체로 만듬 |
$.param() | 객체의 내용을 요청 매개변수 문자열로 만듬 |
$.ajax()
형태는 다음과 같습니다.
$.ajax(options);
$.ajax(url, options);
먼저 서버를 다음과 같이 구성해줍니다.
const express = require("express");
const app = express();
app.use(express.static("public"));
app.all("/data.html", (request, response) => {
response.send("<h1>안녕</h1>")
})
const PORT = 3456;
app.listen(PORT, () => {
console.log(`server running at port ${PORT}`);
})
그런 다음 클라이언트 측에서 $.ajax() 메서드를 사용하여 ajax 요청을 해보겠습니다.
$.ajax() 메서드는 Ajax가 성공하면 자동으로 success 이벤트를 실행합니다.
$(document).ready(() => {
$.ajax({
url: "/data.html",
success: data => $("body").append(data)
})
})
서버를 구동하고 localhost:3456에 접속하면 성공적으로 데이터를 받아온 것을 알 수 있습니다.
만약 jQuery를 사용하지 않고 바닐라 자바스크립트의 XMLHttpRequest 객체를 이용해서 구현하려면 다음과 같이 해야했을 겁니다. 비교해보니 jQuery를 이용한 방법이 훨씬 간단해 보이네요.
const request = new XMLHttpRequest();
request.open("GET", "/data.html", true);
request.send();
request.addEventListener("readystatechange", () => {
if (request.readyState == 4 && request.status == 200) {
document.body.innerHTML += request.responseText;
}
})
이번에는 요청 매개변수까지 $.ajax() 메서드를 이용해 전달해 보겠습니다.
$.ajax({
url: "/parameter",
type: "GET",
data: {
name: "test",
region: "seoul"
},
success: data => $("body").append(data)
})
서버 역시 다음 코드를 추가해줍니다.
실행해보면 정상적으로 받아오는 것을 확인할 수 있습니다.
// ...
app.all("/parameter", (request, response) => {
const name = request.param("name");
const region = request.param("region");
response.send(`<h1>name=${name}, region=${region}</h1>`);
})
jQuery가 지원하는 추가적인 Ajax 메서드를 사용하면 $.ajax() 메서드를 더 간단하게 사용할 수 있습니다.
위에 표에 나온 $.get(), $.post(), $.getJSON 등이 그 예입니다.
사용 형태는 다음과 같습니다.
$(document).ready(() => {
$.get("/data.html", data => $("body").html(data));
})
하지만 위 코드처럼 HTML 태그를 가져와서 문서 객체에 출력할 때는 $(selector).load() 메서드를 사용하는 것이 더 간편합니다. 예제는 다음과 같고, 실행 결과도 위와 동일합니다.
$(document).ready(() => {
$("body").load("/data.html");
})
JSON을 가져올 때는 $.getJSON() 메서드를 사용합니다.
서버에서 JSON 형식으로 데이터를 보내기 위해 다음 코드를 추가합니다.
// ...
const ITEMS = [{
name: "허니버터칩",
price: 1500
}, {
name: "스윙칩",
price: 1300
}, {
name: "꼬북칩",
price: 2000
}]
app.all("/data.json", (request, response) => {
response.send(ITEMS);
})
// ...
만약 XMLHttpRequest 객체를 통해 서버에서 보낸 JSON을 받았다면 다시 JSON.parse() 메서드를 통해 자바스크립트 객체로 변환해주어야 합니다.
하지만 jQuery의 $.getJSON() 메서드를 사용하면 따로 손볼 것이 없습니다.
아래 코드는 XMLHttpRequest 객체를 이용한 방법과 $.getJSON() 메서드를 이용한 방법을 비교한 것입니다.
// XMLHttpRequest 객체를 이용한 Ajax
const request = new XMLHttpRequest();
request.open("GET", "/data.json", true);
request.send();
request.addEventListener("readystatechange", () => {
if (request.status == 200 && request.readyState == 4) {
const data = JSON.parse(request.responseText);
data.forEach(value => {
document.body.innerHTML += `<h1>${value.name}:${value.price}</h1>\n`;
})
}
})
// ============================================================================================
// $.getJSON() 메서드를 이용한 Ajax
$(() => {
$.getJSON("/data.json", data => {
$.each(data, (key, value) => {
$("body").append(`<h1>${value.name}:${value.price}</h1>`);
})
})
})
보조 메서드
먼저 $.param() 메서드부터 알아보겠습니다.
$.param() 메서드는 객체를 쿼리 문자열로 변경해주는 메서드입니다.
비교적 간단하므로 예제를 보면 바로 이해할 수 있습니다.
$(() => {
const data = {
name: "seungsu",
region: "seoul"
};
$("<h1></h1>").text($.param(data)).appendTo("body");
})
위 코드를 웹 브라우저에서 실행해보면 다음과 같이 나타납니다.
객체를 아래와 같은 쿼리 스트링으로 바꿔주는 메서드 $.param()입니다.
name=seungsu®ion=seoul