Advertisement
Guest User

Untitled

a guest
Mar 30th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. function attachEvents() {
  2. const URL = 'https://baas.kinvey.com/appdata/kid_H1W44cKcz/';
  3. const USERNAME = 'peter';
  4. const PASSWORD = 'p';
  5. const BASE_64 = btoa(USERNAME + ':' + PASSWORD);
  6. const AUTH = {'Authorization': 'Basic ' + BASE_64};
  7. const POSTS = $('#posts');
  8. const POSTCOMMENTS = $('#post-comments');
  9.  
  10. $('#btnLoadPosts').on('click', getPosts);
  11. $('#btnViewPost').on('click', viewPost);
  12.  
  13. function getPosts() {
  14. $.ajax({
  15. method: 'GET',
  16. url: URL + 'posts',
  17. headers: AUTH
  18. }).then(appendPosts);
  19.  
  20. function appendPosts(posts) {
  21. POSTS.empty();
  22. for (let post in posts) {
  23. let newOption = $(`<option value="${posts[post]._id}">${posts[post].title}</option>`);
  24. POSTS.append(newOption);
  25. }
  26. }
  27. }
  28.  
  29. function viewPost() {
  30. let postId = $('#posts').find(":selected")[0];
  31.  
  32. $.ajax({
  33. method: 'GET',
  34. url: URL + 'posts' + '/' + postId.value,
  35. headers: AUTH
  36. }).then(changeText);
  37.  
  38. $.ajax({
  39. method: 'GET',
  40. url: URL + `comments/?query={"post_id":"${postId.value}"}`,
  41. headers: AUTH
  42. }).then(displayComments);
  43.  
  44. function changeText(returnedPost) {
  45. $('#post-title').text(returnedPost.title);
  46. $('#post-body').text(returnedPost.body);
  47. }
  48.  
  49. function displayComments(comments) {
  50. POSTCOMMENTS.empty();
  51. for (let comment in comments) {
  52. let currentComment = $(`<li>${comments[comment].title}</li>`);
  53. POSTCOMMENTS.append(currentComment);
  54. }
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement