Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function attachEvents() {
- const kinveyAppId = "kid_S12g5Xa8W";
- const serviceUrl = "https://baas.kinvey.com/appdata/" + kinveyAppId;
- const kinveyUsername = "peter";
- const kinveyPassword = "p";
- const base64auth = btoa(kinveyUsername + ":" + kinveyPassword);
- const authHeaders = { "Authorization": "Basic " + base64auth };
- $('#btnLoadPosts').click(loadPostsClick);
- $('#btnViewPosts').click(viewPostClick);
- function loadPostsClick() {
- let loadPostRequest = {
- method: "GET",
- url: serviceUrl + "/posts/",
- headers: authHeaders
- }
- $.ajax(loadPostRequest)
- .then(displayPosts)
- .catch(displayError)
- };
- function displayPosts(posts) {
- $('#posts').empty();
- for (let post of posts) {
- $('#posts').append($('<option>').text(post.title).val(post._id))
- }
- }
- function viewPostClick() {
- let selectedPostID = $('#posts').val();
- if (!selectedPostID) {
- return;
- }
- let requestPost = $.ajax({
- method: "GET",
- url: serviceUrl + "/posts/" + selectedPostID,
- headers: authHeaders
- });
- let requestComments = $.ajax({
- url: serviceUrl + `/comments/?query={"post_id":"${selectedPostID}"}`,
- headers: authHeaders });
- Promise.all([requestPost, requestComments])
- .then(displayPostWithComments)
- .catch(displayError)
- }
- function displayPostWithComments([post, comments]) {
- $('#post-title').text(post.title);
- $('#post-body').text(post.body);
- $('#post-comments').empty();
- for (let comment of comments) {
- $('#post-comments').append($("<li>").text(comment.text))
- }
- }
- function displayError(err) {
- let errDiv = $('<div>').text("Error: " + err.status + " (" + err.statusText + ")");
- $(document.body).prepend(errDiv);
- setTimeout(function () {
- $(errDiv).fadeOut(function () {
- $(errDiv).remove();
- })
- }, 3000)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement