Advertisement
Kamend1

01.Blog

Apr 3rd, 2025
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.     let postsUrl = 'http://localhost:3030/jsonstore/blog/posts';
  3.     let commentsUrl = 'http://localhost:3030/jsonstore/blog/comments';
  4.  
  5.     let loadBtn = document.getElementById('btnLoadPosts');
  6.     let viewBtn = document.getElementById('btnViewPost');
  7.  
  8.     let selectSection = document.getElementById('posts');
  9.     let postTitle = document.getElementById('post-title');
  10.     let postBody = document.getElementById('post-body');
  11.     let list = document.getElementById('post-comments');
  12.  
  13.     loadBtn.addEventListener('click', loadPosts);
  14.     viewBtn.addEventListener('click', loadComments);
  15.  
  16.     async function loadPosts () {
  17.         try {
  18.             let posts = await fetch(postsUrl);
  19.             let postData = await posts.json();
  20.  
  21.             let postEntries = Object.entries(postData);
  22.  
  23.             for (let [key, post] of postEntries) {
  24.                 let newOption = document.createElement('option');
  25.                 newOption.value = key;
  26.                 newOption.textContent = post.title;
  27.  
  28.                 selectSection.appendChild(newOption);
  29.             }
  30.  
  31.         } catch (error) {
  32.             console.error(error);
  33.         }
  34.     }
  35.  
  36.     async function loadComments () {
  37.         let currentKey = selectSection.value;
  38.         let currentPost;
  39.  
  40.         try {
  41.             let posts = await fetch(postsUrl);
  42.             let postData = await posts.json();
  43.  
  44.             let currentPost = postData[currentKey];
  45.  
  46.             postTitle.textContent = currentPost.title;
  47.             postBody.textContent = currentPost.body;
  48.  
  49.         } catch (error) {
  50.             console.error(error);
  51.         }
  52.  
  53.         try {
  54.             let comments = await fetch(commentsUrl);
  55.             let commentsData = await comments.json();
  56.             list.innerHTML = '';
  57.            
  58.             let filteredComments = Object.values(commentsData).filter(c => c.postId === currentKey);
  59.  
  60.             filteredComments.forEach(comment => {
  61.                 const li = document.createElement('li');
  62.                 li.textContent = comment.text;
  63.                 list.appendChild(li);
  64.             });
  65.  
  66.         } catch (error) {
  67.             console.log(error);
  68.         }
  69.     }
  70.  
  71. }
  72.  
  73. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement