Search JS
- 순서대로 보면서 이해하기
1. html에서 검색 onclick 함수를 만들어 준다. (searchFilter)
2.article-search id를 가진 요소의 값을 찾아 input_value 변수 값에 할당한다. (html)
3. fetch 함수를 사용하여 서버에 GET요청을 보낸다.(backend_base_url)
async function searchFilter() {
const input_value = document.getElementById("article-search").value;
const response = await fetch(`${backend_base_url}/article/search/?search=${input_value}`, {
method: 'GET'
});
Search 오류 발생
1. feed-article 값을 html에 적용을 했다 하지만 전체적으로 검색은 불가능..
2. 팀원들에게 도움 요청
이유: feed- article 즉 검색을 사용할 html에 feed-article id 값을 전체적으로 묶어줘야한다.
const response_json = await response.json();
const cardsBox = document.getElementById("feed-article");
if (!cardsBox) {
console.error("feed-article 요소를 찾을 수 없습니다.");
return;
}
Search JS
4. cardsBox 내용을 비운다. ()
5.!result.image image 속성이 존재하지 않는 경우, 다음 요소로 건너뛴다
cardsBox.innerHTML = '';
response_json.forEach((result) => {
if (!result.image) {
// 대체 이미지 또는 기본 텍스트를 사용하거나, 해당 항목을 건너뛸 수 있음
return;
}
6. <a> 요소를 생성 , class 속성을 추가
const cardLink = document.createElement("a");
cardLink.setAttribute("href", `/article/detail.html?article_id=${result.id}`);
cardLink.setAttribute("class", "card-link");
7. class ,id 속성을 설정 하고 'http://backend:8000' 부분을 'https://www.nuriggun.xyz'로 대체하여 이미지의 소스를 설정 (서버 배포후 이부분 추가 )
const image = document.createElement("img");
image.setAttribute("class", "card-img-top");
let imageSrc = result.image.replace('http://backend:8000', 'https://www.nuriggun.xyz');
image.setAttribute("src", imageSrc);
const title = document.createElement("h5");
title.setAttribute("class", "card-title");
title.textContent = result.title;
const category = document.createElement("h6");
category.setAttribute("class", "card-category");
category.textContent = result.category;
const content = document.createElement("p");
content.setAttribute("class", "card-text");
content.textContent = result.content;
8. 편리함을?! 위해 글자 제한 수을 걸었다.
const maxLength = 20;
if (result.content.length > maxLength) {
content.textContent = result.content.substring(0, maxLength) + "...";
} else {
content.textContent = result.content;
}
9.cardLink에 newCard를 추가하고, cardsBox에 cardLink를 추가합니다. 이 과정을 response_json 배열의 모든 요소에 대해 반복
cardBody.appendChild(category);
cardBody.appendChild(title);
cardBody.appendChild(content);
newCard.appendChild(image);
newCard.appendChild(cardBody);
cardLink.appendChild(newCard);
cardsBox.appendChild(cardLink);
});
댓글