Advertisement
braveheart1989

Блог

Nov 19th, 2016
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.     const baseServiceUrl = 'https://baas.kinvey.com/appdata/kid_SJo3fInbe';
  3.     const userName = "peter";
  4.     const password = "1";
  5.     const base64auth = btoa(userName + ":" + password);
  6.     const authHeaders = {"Authorization": "Basic " + base64auth};
  7.  
  8.     $('#btnLoadPosts').click(loadAllPosts);
  9.     $('#btnViewPost').click(viewPost);
  10.     function displayPosts(data) {
  11.         let allPosts = $('#posts');
  12.         for (let opt of data) {
  13.             let option = $('<option>').val(opt._id).text(opt.title);
  14.             allPosts.append(option)
  15.         }
  16.     }
  17.  
  18.     function displayError(error) {
  19.         $('#post-body').text('Error ' + error.status +" " + error.statusText)
  20.     }
  21.  
  22.     function loadAllPosts() {
  23.         let request = {
  24.             method:"GET",
  25.             url:baseServiceUrl + '/posts',
  26.             headers:authHeaders
  27.         };
  28.         $.ajax(request)
  29.             .then(displayPosts)
  30.             .catch(displayError)
  31.     }
  32.  
  33.     function displayPostWithComments([post, comments]) {
  34.         $("#post-title").text(post.title);
  35.         $("#post-body").text(post.body);
  36.         for (let comment of comments) {
  37.             let li = $('<li>').text(comment.text);
  38.             $('#post-comments').append(li);
  39.         }
  40.     }
  41.  
  42.     function viewPost() {
  43.         let id = $("option:selected").val();
  44.         let request = {
  45.             method:"GET",
  46.             url:baseServiceUrl + '/posts/' + id,
  47.             headers:authHeaders
  48.         };
  49.         let post = $.ajax(request);
  50.         let requestComment = $.ajax({
  51.             method:"GET",
  52.             url:baseServiceUrl + `/comments/?query={"post_id":"${id}"}`,
  53.             headers:authHeaders
  54.         });
  55.         $.ajax(requestComment);
  56.         Promise.all([post, requestComment])
  57.             .then(displayPostWithComments)
  58.             .catch(displayError);
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement