- jsonplaceholder
- news
- pixabay
1) jsonplaceholder
jsonplaceholder post api를 이용해 게시판을 만들어 보았다.
https://jsonplaceholder.typicode.com/
JSONPlaceholder - Free Fake REST API
{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. Serving ~2 billion requests each month.
jsonplaceholder.typicode.com
<script>
const tbody = document.querySelector('.board .table-body');
const paging = document.querySelector('.board .paging');
const url = 'https://jsonplaceholder.typicode.com/posts';
let posts, postsPerPage = 10, currentPage = 1
let firstPost, lastPost, postMod, pageNumber, totalPage
let a = '';
const getData = async () => {
const res = await fetch(url);
const myJson = await res.json();
posts = myJson;
totalPage = posts.length;
postMod = totalPage % postsPerPage;
pageNumber = Math.ceil(totalPage / postsPerPage)
for (let i = 1; i <= pageNumber; i++) {
a += `<a>${i}</a>`
}
paging.innerHTML = a
tableIn(currentPage)
let aAll = document.querySelectorAll('.paging a')
aAll[currentPage - 1].classList.add('on')
let old = 0;
aAll.forEach((item, idx) => {
item.addEventListener('click', e => {
let ele = e.currentTarget
if (old !== idx) {
ele.classList.add('on')
aAll[old].classList.remove('on')
tableIn(idx + 1)
old = idx
}
})
})
}
function tableIn(currentPage) {
console.log(currentPage)
let row = '';
lastPost = currentPage * postsPerPage;
firstPost = lastPost - postsPerPage;
if (postMod !== 0 && currentPage === pageNumber) {
lastPost = firstPost + postMod
}
for (let i = firstPost; i < lastPost; i++) {
row += `<tr>
<td> ${posts[i].id} </td>
<td> ${posts[i].title} </td>
<td> ${posts[i].body} </td>
</tr>
`
}
tbody.innerHTML = row;
}
getData();
</script>
await와 fetch를 사용해 비동기통신을 하고, 총 페이지와 페이지당 표시될 post 숫자를 계산해 게시판 하단에 paging 버튼을 추가해 준다.
let aAll = document.querySelectorAll('.paging a')
aAll[currentPage - 1].classList.add('on')
let old = 0;
aAll.forEach((item, idx) => {
item.addEventListener('click', e => {
let ele = e.currentTarget
if (old !== idx) {
ele.classList.add('on')
aAll[old].classList.remove('on')
tableIn(idx + 1)
old = idx
}
})
})
그 뒤에 버튼 클릭 시 class가 add 되게 해 준다.
마지막으로 tableIn 함수에서는 currentPage를 매개변수로 받아 page에 맞는 post 번호만 tbody에 출력되게 해 주었다.
2) news
https://newsapi.org/s/south-korea-news-api
South Korea News API - Live top headlines from South Korea
Get live top and breaking news headlines from South Korea with our JSON API. Live example This example demonstrates the HTTP request to make, and the JSON response you will receive, when you use the News API to get live headlines from South Korea. Top head
newsapi.org
<body>
<main id="container" class="news">
<section id="content">
<div class="inner">
<!-- <article>
<a href="">
<h2>타이틀</h2>
<img src="" alt="">
<p></p>
</a>
</article> -->
</div>
</section>
</main>
<script>
const article = document.querySelector('.inner')
const url = 'https://newsapi.org/v2/top-headlines?country=kr
fetch(url)
.then(res=>res.json())
.then(res=>{
console.log(res.articles);
listIn(res.articles)
})
function listIn(data) {
for (let i = 0; i < data.length; i++) {
article.innerHTML += `
<article>
<a href="${data[i].url}}">
<h2>${data[i].title}</h2>
<img src="${data[i].urlToImage}" alt="">
<p>${data[i].description}</p>
</a>
</article>
`
}
}
</script>
</body>
3) pixabay
Pixabay API Documentation
lang str Language code of the language to be searched in. Accepted values: cs, da, de, en, es, fr, id, it, hu, nl, no, pl, pt, ro, sk, fi, sv, tr, vi, th, bg, ru, el, ja, ko, zh Default: "en" category str Filter results by category. Accepted values: backgr
pixabay.com
<script>
let conBox = document.querySelector('.con-box')
let search = document.querySelector('#text')
let form = document.querySelector('#form')
let searchBtn = document.querySelector('button')
let url, keyword;
const getData = async(keyword='')=>{
url = `https://pixabay.com/api/?key==${keyword}&image_type=photo`;
const res = await fetch(url)
const myJson = await res.json();
show(myJson.hits)
}
function show(data) {
conBox.innerHTML = '';
for (let i = 0; i < data.length; i++) {
let tages = data[i].tags.split(',');
conBox.innerHTML += `
<article>
<div>
<img src="${data[i].largeImageURL}" alt="">
</div>
<h3>${data[i].user}</h3>
<ul>
<li><span>view</span>:<em>${data[i].views}</em></li>
<li><span>download</span>:<em>${data[i].downloads}</em></li>
<li><span>like</span>:<em>${data[i].likes}</em></li>
</ul>
<p>
<span>#${tages[0]}</span>
<span>#${tages[1]}</span>
<span>#${tages[2]}</span>
</p>
</article>
`;
}
}
form.addEventListener('submit', e => {
e.preventDefault();
keyword = search.value;
getData(keyword);
});
</script>
pixabay api의 경우 검색하고자 하는 키워드를 url에 넣으면 이미지를 불러와 준다.
const getData = async(keyword='')=>{
url = `https://pixabay.com/api/?key==${keyword}&image_type=photo`;
const res = await fetch(url)
const myJson = await res.json();
show(myJson.hits)
}
따라서 input으로 받은 keyword를 url에 넣어주었다.
처음 keyword는 async(keyword=' ')으로 공백이므로 첫 화면엔 아무것도 출력이 되지 않는다.
* form에 event를 걸 경우 출력 후 새로고침이 되므로 preventDefault()를 넣어주어야 한다.
e.preventDefault();
만약 input에 keyword를 넣고 search 버튼을 눌렀을 때 같은 결과를 나오게 하고 싶다면 아래 코드를 추가하면 된다.
searchBtn.addEventListener('click', e => {
e.preventDefault();
keyword = search.value;
getData(keyword);
});