Advertisement
GeorgiLukanov87

04. Blog

Mar 25th, 2023
782
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 04. Blog
  2. // HTTP and REST - Exercises
  3. // https://judge.softuni.org/Contests/Compete/Index/3798#3
  4.  
  5.  
  6. function attachEvents() {
  7.     let postElement = document.getElementById('posts');
  8.     const loadBtnElement = document.getElementById('btnLoadPosts');
  9.     const viewBtnElement = document.getElementById('btnViewPost');
  10.     const postBody = document.getElementById('post-body');
  11.     const postTitle = document.getElementById('post-title');
  12.     const postComments = document.getElementById('post-comments');
  13.  
  14.     loadBtnElement.addEventListener('click', loadPosts)
  15.     viewBtnElement.addEventListener('click', viewComments)
  16.  
  17.     let getPosts = {};
  18.  
  19.     function loadPosts() {
  20.         fetch(`http://localhost:3030/jsonstore/blog/posts`).then(response => response.json())
  21.             .then(data => {
  22.                 postElement.innerHTML = ''
  23.                 for (let objKey in data) {
  24.                     let value = data[objKey]["id"];
  25.                     let body = data[objKey]["body"];
  26.                     let title = data[objKey]['title'];
  27.                     if (!(value in getPosts)) {
  28.                         getPosts[value] = body
  29.                     }
  30.  
  31.                     let newValue = document.createElement('option');
  32.                     newValue.value = value;
  33.                     newValue.textContent = title;
  34.  
  35.                     postElement.appendChild(newValue);
  36.                 }
  37.  
  38.             })
  39.  
  40.     }
  41.  
  42.     function viewComments() {
  43.         fetch('http://localhost:3030/jsonstore/blog/comments').then(response => response.json())
  44.             .then(data => {
  45.                 postComments.innerHTML = ''
  46.                 let commentKey = postElement.value;
  47.                 let commentText = postElement.options[postElement.selectedIndex].text;
  48.                 postTitle.textContent = commentText;
  49.                 for (let i in data) {
  50.                     if (data[i]['postId'] === commentKey) {
  51.                         let newLiComment = document.createElement('li')
  52.                         newLiComment.setAttribute('id', data[i]['id'])
  53.                         newLiComment.textContent = data[i]['text']
  54.                         postComments.appendChild(newLiComment)
  55.                         postBody.textContent = getPosts[commentKey]
  56.  
  57.                     }
  58.  
  59.                 }
  60.             })
  61.     }
  62.  
  63. }
  64.  
  65. attachEvents();
  66.  
  67.  
  68.  
  69.  
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement