반응형
🔌API 통합 실전
이번 강좌에서는 jQuery와 외부 REST API를 통합하여 실제 데이터를 불러오고 화면에 출력하는 실습을 해봅니다.
우리가 사용할 API는 JSONPlaceholder이며, 게시글 데이터를 받아와 리스트 형태로 출력할 것입니다.
📦 1. HTML 기본 구조
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>jQuery API Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body { font-family: 'Malgun Gothic', sans-serif; padding: 30px; }
h2 { color: #2980b9; }
#postList { margin-top: 20px; padding-left: 0; list-style: none; }
#postList li { padding: 10px; border-bottom: 1px solid #eee; }
</style>
</head>
<body>
<h2>📃 게시글 목록 불러오기</h2>
<button id="loadBtn">게시글 불러오기</button>
<ul id="postList"></ul>
</body>
</html>
⚙️ 2. jQuery로 API 요청
버튼을 클릭하면 Ajax를 통해 외부 API에서 데이터를 받아옵니다.
<script>
$(function () {
$('#loadBtn').on('click', function () {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'GET',
dataType: 'json',
success: function (data) {
let html = '';
data.slice(0, 10).forEach(post => {
html += `<li><strong>${post.title}</strong><br>${post.body}</li>`;
});
$('#postList').html(html);
},
error: function () {
alert('데이터를 불러오는 데 실패했습니다.');
}
});
});
});
</script>
여기서 slice(0, 10)은 게시글 중 상위 10개만 출력하기 위해 사용합니다.
🔄 3. 고급: 로딩 표시 및 에러 처리
사용자 경험 향상을 위해 로딩 메시지와 에러 메시지를 추가해 보세요.
$('#loadBtn').on('click', function () {
$('#postList').html('<li>🔄 불러오는 중입니다...</li>');
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'GET',
dataType: 'json',
success: function (data) {
let html = '';
data.slice(0, 10).forEach(post => {
html += `<li><strong>${post.title}</strong><br>${post.body}</li>`;
});
$('#postList').html(html);
},
error: function () {
$('#postList').html('<li style="color:red;">❌ 오류: 데이터를 불러올 수 없습니다.</li>');
}
});
});
📚 확장 아이디어
- 검색어 입력 시 쿼리 파라미터를 추가하여 필터링
- 댓글 목록도 함께 불러오는 기능 추가
- 페이지네이션 구현
- 게시글 상세보기 모달창 연결
반응형
'Programming' 카테고리의 다른 글
| React 개발 환경 (71) | 2025.10.17 |
|---|---|
| React 소개 (59) | 2025.10.16 |
| jQuery 유지보수성과 재사용성 (66) | 2025.10.14 |
| jQuery SPA(Single Page Application) 구축하기 (55) | 2025.10.12 |
| jQuery 이벤트 위임과 동적 요소 처리 (54) | 2025.10.11 |