국가 정보를 가져와서 화면에 출력하기
-> 국가명, 국가 이미지, 지도, 링크 등을 출력
엔드포인트 ⇒ https://restcountries.com/v3.1/all
필드 설명 ⇒ https://gitlab.com/restcountries/restcountries/-/blob/master/FIELDS.md
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- axios, jquery 라이브러리 추가 -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.js"
integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script>
</script>
</head>
<body>
<h1>국가 정보를 가져와서 출력</h1>
<ul></ul>
</body>
</html>
<script>
axios.get("https://restcountries.com/v3.1/all") // 엔드포인트
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
</script>
<li> 요소로 출력res.data.forEach(country => {
/* 데이터의 구조를 파악해서 원하는 데이터를 추출
console.log(country.name.official);
console.log(country.flags.png);
console.log(country.maps.googleMaps);
console.log(country.maps.openStreetMaps);
console.log("---------------");
*/
const li = `
<li>
<img src="${country.flags.png}" alt="${country.flags.alt}" />
<p>${country.name.common} (${country.name.official})</p>
</li>
`;
$('ul').append(li);
HTML에서 <ul>(unordered list)과 <li>(list item)는 리스트(목록)를 표현하기 위해 사용한다
<ul>: 전체 목록을 감싸는 태그 <li>: 목록의 개별 항목을 정의하는 태그로 아래와 같이 사용한다.<ul>
<li>첫 번째 항목</li>
<li>두 번째 항목</li>
</ul>
여기서는 li 변수에 HTML 형식의 문자열로 <li>를 정의하였고.
$('ul').append(li)와 같이 jQuery로 <ul> 안에 <li>를 추가하였다.
<style>
img { width: 100px; height: auto; }
p { display: inline; }
</style>
-> 이미지 너비와 높이를 설정해주고 텍스트를 한줄로 출력한다
부트 스트랩은 웹 디자인을 빠르고 간편하게 적용하기 위한 것으로, 미리 만들어진 디자인들을 명령 규칙에 따라 적용만 하면 사용 가능
class="bg-light": 부트스트랩 클래스 중 하나로, 배경색을 연한 회색으로 설정div class="container my-5 : 부트스트랩의 컨테이너 클래스를 사용해 페이지 내용을 중앙 정렬하고, 일정 폭을 유지, my-5는 상하 마진(여백)을 추가<ul class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-3"></ul><ul> 태그는 국가 정보를 출력하기 위한 목록이다.row: 그리드 시스템의 행(Row)을 생성.
row-cols-1: 모바일 화면(기본 크기)에서는 한 줄에 1개 열(Column) 표시.
row-cols-md-2: 중간 크기 화면(md)에서는 한 줄에 2개 열 표시.
row-cols-lg-3: 큰 화면(lg)에서는 한 줄에 3개 열 표시.
g-3: 각 열(Column) 사이에 일정한 간격(Gap)을 추가.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- axios, jquery 라이브러리 추가 -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.js"
integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<!-- Bootstrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
<script>
axios.get("https://restcountries.com/v3.1/all")
.then(res => {
console.log(res);
res.data.forEach(country => {
const li = `
<li class="d-flex align-items-center border p-3 bg-white rounded shadow-sm">
<img src="${country.flags.png}" alt="${country.flags.alt}" class="img-fluid rounded" />
<p class="mb-0 ms-3">${country.name.common} (${country.name.official})</p>
</li>
`;
$('ul').append(li);
});
})
.catch(err => {
console.log(err);
});
</script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<style>
img { width: 100px; height: auto; margin-right: 10px; }
ul { padding: 0; }
li { list-style-type: none; margin-bottom: 20px; }
</style>
</head>
<body class="bg-light">
<div class="container my-5">
<h1 class="text-center text-primary mb-4">국가 정보를 가져와서 출력</h1>
<ul class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-3"></ul>
</div>
</body>
</html>
검색창에서 입력 이벤트 감지
-> 사용자가 검색창에 글자를 입력할 때마다 키보드 이벤트(keyup)가 발생
$('input').on('keyup', e => {
const inputText = $(e.currentTarget).val().toLowerCase();
// 현재 입력창에 입력된 텍스트를 가져와 모두 소문자를 변환
});
필터링 로직
.indexOf(inputText): 국가 이름에 입력된 텍스트가 포함되어 있으면, 해당 텍스트의 위치를 반환, 포함되어 있지 않으면 -1을 반환.filteredData 배열에 저장const filteredData = datas.filter(data =>
data.name.common.toLowerCase().indexOf(inputText) >= 0 ||
data.name.official.toLowerCase().indexOf(inputText) >= 0
);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- axios, jquery 라이브러리 추가 -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.1.js"
integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<!-- Bootstrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
<script>
// 서버로 부터 가져온 전체 국가 정보를 저장할 배열
let datas = [];
// 국가 정보를 담고 있는 배열을 출력
const showCountryInfo = countryInfos => {
$('ul').empty();
countryInfos.forEach(country => {
const li = `
<li class="d-flex align-items-center border p-3 bg-white rounded shadow-sm">
<img src="${country.flags.png}" alt="${country.flags.alt}" class="img-fluid rounded" />
<p class="mb-0 ms-3">${country.name.common} (${country.name.official})</p>
</li>
`;
$('ul').append(li);
});
};
axios.get("https://restcountries.com/v3.1/all")
.then(res => {
datas = [...res.data];
showCountryInfo(res.data);
})
.catch(err => {
console.log(err);
});
</script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<style>
img { width: 100px; height: auto; margin-right: 10px; }
/*
p { display: inline; }
*/
ul { padding: 0; }
li { list-style-type: none; margin-bottom: 20px; }
</style>
</head>
<body class="bg-light">
<div class="container my-5">
<h1 class="text-center text-primary mb-4">국가 정보를 가져와서 출력</h1>
<div class="d-flex justify-content-center mb-4">
<input type="text" class="form-control" placeholder="검색할 국가명을 입력하세요." />
</div>
<ul class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-3"></ul>
</div>
<script>
$('input').on('keyup', e => {
const inputText = $(e.currentTarget).val().toLowerCase();
console.log(inputText); // 현재 입력창에 입력된 내용(글자)
// 서버로부터 가져온 국가 정보에서 국가명에 입력창의 내용이 포함된 건만 추출해서 출력
// ~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~ ~~~~~~~~~~~~ ~~~~~~~~~~~~~~ ~~~
// datas datas[*].name.common inputText | showCountryInfo()
// datas[*].name.official +-- Array.filter()
const filteredData = datas.filter(data =>
data.name.common.toLowerCase().indexOf(inputText) >= 0 ||
data.name.official.toLowerCase().indexOf(inputText) >= 0
);
showCountryInfo(filteredData);
});
</script>
</body>
</html>