Liliana797979

blog - js apllications

Nov 5th, 2021
1,181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.  
  3.     $('#btnLoadPosts').on('click', loadPosts);
  4.     $('#btnViewPost').on('click', loadPost);
  5.     const mainURL = 'https://baas.kinvey.com/appdata/kid_SJNmiOkwb/';
  6.     const credentials = 'pesho:p';
  7.     let postsOption = $('#posts');
  8.     let comments = $('#post-comments');
  9.  
  10.  
  11.     loadPosts();
  12.  
  13.     async function loadPost() {
  14.         let selectedPost = $('option:selected');
  15.         let postData = await getPostData(selectedPost.val());
  16.  
  17.         $('#post-title').text(`${postData.title}`);
  18.         $('#post-body').text(`${postData.body}`);
  19.        
  20.         let commentsData = await getCommentsData(selectedPost.val());
  21.         comments.empty();
  22.         for (let comment in commentsData) {
  23.             comments.append($('<li>').text(commentsData[comment]['text']));
  24.         }
  25.         // 10001
  26.     }
  27.  
  28.     async function getCommentsData(postId) {
  29.         return await $.ajax({
  30.             url: `${mainURL}comments/?query={"post_id":"${postId}"}`,
  31.             method: 'GET',
  32.             headers: {
  33.                 'Authorization': `Basic ${btoa(credentials)}`
  34.             }
  35.         });
  36.     }
  37.     async function getPostData(postId) {
  38.         return await $.ajax({
  39.             url: `${mainURL}posts/${postId}`,
  40.             method: 'GET',
  41.             headers: {
  42.                 'Authorization': `Basic ${btoa(credentials)}`
  43.             }
  44.         });
  45.     }
  46.  
  47.     async function loadPosts(data) {
  48.         let posts = await getPosts();
  49.  
  50.         for (let postId in posts) {
  51.             postsOption.append($('<option>').text(posts[postId].title).val(posts[postId]['_id']));
  52.         }
  53.  
  54.     }
  55.  
  56.     async function getPosts() {
  57.         return await $.ajax({
  58.             url: `${mainURL}posts`,
  59.             method: 'GET',
  60.             headers: {
  61.                 'Authorization': `Basic ${btoa(credentials)}`
  62.             }
  63.         });
  64.     }
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment