// script.js
// DOM이 로드된 후 실행될 함수를 등록합니다.
document.addEventListener('DOMContentLoaded', function () {
/*
console.log(window.location.href);
console.log(window.location.protocol);
console.log(window.location.host);
console.log(window.location.hostname);
console.log(window.location.port);
console.log(window.location.pathname);
console.log(window.location.search);
*/
let Pr = window.location.protocol;
let Hostname = window.location.hostname;
let PrHo = Pr+"//"+Hostname
async function play() {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', PrHo+'/api/news?page=0&size=2', true);
xhr.onload = function () {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
resolve(data.totalElements); // 비동기 작업이 성공적으로 완료되면 resolve를 호출합니다.
} else {
reject("Error " + xhr.status); // 비동기 작업이 실패하면 reject를 호출합니다.
}
};
xhr.onerror = function () {
reject("Network error");
};
xhr.send();
});
}
async function play_1(number) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', PrHo+`/api/news?page=${number}&size=2`, true);
xhr.onload = function () {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
resolve(data.content); // 비동기 작업이 성공적으로 완료되면 resolve를 호출합니다.
} else {
reject("Error " + xhr.status); // 비동기 작업이 실패하면 reject를 호출합니다.
}
};
xhr.onerror = function () {
reject("Network error");
};
xhr.send();
});
}
// 예시 데이터, 이 부분에서는 서버로부터 받아온 게시글 데이터를 모방합니다.
// 실제 애플리케이션에서는 이 배열이 서버로부터 동적으로 받아온 데이터일 것입니다.
const postsPerPage = 2; // 페이지 당 보여줄 게시글의 수를 정의합니다.
let currentPage = 1; // 현재 페이지를 나타내는 변수, 초기값은 1 페이지입니다.
// 현재 페이지에 해당하는 게시글들을 화면에 렌더링하는 함수입니다.
async function renderPosts() {
const postsContainer = document.getElementById('posts-container');
postsContainer.innerHTML = ''; // 게시글을 담는 컨테이너를 초기화합니다.
// 현재 페이지에 보여줄 게시글의 범위를 계산합니다.
const start = (currentPage - 1) * postsPerPage;
const end = start + postsPerPage;
let box_content = await play_1(currentPage - 1);
//console.log(box_content);
// slice를 사용하여 현재 페이지에 해당하는 게시글 부분집합을 가져옵니다.
const paginatedPosts = box_content.slice(0,2);
//posts.slice(start, end);
if(paginatedPosts.length<2)
{
paginatedPosts.forEach(async post => {
let img = PrHo+"/api/news/image?id=" + post.id;
let text = post.title;
let content = post.content;
let maxLength = 20;
if(text.length > maxLength) {
post.title = text.substring(0, maxLength) + '...';
}
if(content.length > maxLength) {
post.content = content.substring(0, maxLength) + '...';
}
const postElement = document.createElement('div');
postElement.classList.add('post-item'); // 스타일 적용을 위한 클래스 추가
postElement.innerHTML = `
${post.title}
${post.content}
`; // 게시글 제목과 내용을 설정
postsContainer.appendChild(postElement); // 생성된 요소를 DOM에 추가
const postElement2 = document.createElement('div');
postElement2.classList.add('post-item'); // 스타일 적용을 위한 클래스 추가
postsContainer.appendChild(postElement2);
});
}
else{
// 각 게시글에 대해 HTML 요소를 생성하고 컨테이너에 추가합니다.
paginatedPosts.forEach(async post => {
//let img = await new_img(1);
let img = PrHo+"/api/news/image?id=" + post.id;
//console.log(post.id);
let text = post.title;
let content = post.content;
let maxLength = 20;
if(text.length > maxLength) {
post.title = text.substring(0, maxLength) + '...';
}
if(content.length > maxLength) {
post.content = content.substring(0, maxLength) + '...';
}
const postElement = document.createElement('div');
postElement.classList.add('post-item'); // 스타일 적용을 위한 클래스 추가
postElement.innerHTML = `
${post.title}
${post.content}
`; // 게시글 제목과 내용을 설정
postsContainer.appendChild(postElement); // 생성된 요소를 DOM에 추가
});
}
}
async function renderPagination() {
let num = await play();
const pagination = document.getElementById('pagination');
pagination.innerHTML = '';
const pageCount = num;
// 이전 페이지 버튼 추가
const prevButton = document.createElement('button');
prevButton.textContent = '<';
prevButton.classList.add('page-item');
prevButton.disabled = currentPage === 1; // 첫 페이지에서는 비활성화
prevButton.addEventListener('click', () => {
currentPage -= 1; // 현재 페이지 번호 감소
renderPosts();
renderPagination();
});
pagination.appendChild(prevButton);
// 숫자 페이지 버튼 추가
for (let i = 1; i <= pageCount; i++) {
const pageItem = document.createElement('button');
pageItem.textContent = i;
pageItem.classList.add('page-item');
if (i === currentPage) {
pageItem.classList.add('active');
}
pageItem.addEventListener('click', () => {
currentPage = i;
renderPosts();
renderPagination();
});
pagination.appendChild(pageItem);
}
// 다음 페이지 버튼 추가
const nextButton = document.createElement('button');
nextButton.textContent = '>';
nextButton.classList.add('page-item');
nextButton.disabled = currentPage === pageCount; // 마지막 페이지에서는 비활성화
nextButton.addEventListener('click', () => {
currentPage += 1; // 현재 페이지 번호 증가
renderPosts();
renderPagination();
});
pagination.appendChild(nextButton);
}
// 초기 게시글 및 페이지네이션 렌더링을 실행합니다.
renderPosts();
renderPagination();
});