Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Parse JSON objects</title>
- </head>
- <body>
- <button onclick="postFunction()">Posts</button>
- <ul id="post"></ul>
- <button onclick="commentFunction()">Comments</button>
- <ul id="comment"></ul>
- <button onclick="profileFunction()">Profiles</button>
- <ul id="profile"></ul>
- <script>
- function postFunction() {
- var xmlhttp = new XMLHttpRequest();
- xmlhttp.onreadystatechange = function () {
- if (this.readyState == 4 && this.status == 200) {
- let myArr = JSON.parse(this.responseText);
- let output = '';
- for (var i = 0; i < myArr.length; i++) {
- output += '<li>' + 'postId: ' + myArr[i].id + '<br>' + ' title: ' + myArr[i].title + '<br>' + ' author: ' + myArr[i].author; '</li>'
- }
- document.getElementById('post').innerHTML = output;
- }
- };
- xmlhttp.open("GET", "http://35.246.169.20:3000/posts", true);
- xmlhttp.send();
- }
- function commentFunction() {
- var xmlhttp = new XMLHttpRequest();
- xmlhttp.onreadystatechange = function () {
- if (this.readyState == 4 && this.status == 200) {
- let myArr = JSON.parse(this.responseText);
- let output = '';
- for (var i = 0; i < myArr.length; i++) {
- output += '<li>' + 'commentId: ' + myArr[i].id + '<br>' + ' body: ' + myArr[i].body + '<br>' + ' postId: ' + myArr[i].postId; '</li>'
- }
- document.getElementById('comment').innerHTML = output;
- }
- };
- xmlhttp.open("GET", "http://35.246.169.20:3000/comments", true);
- xmlhttp.send();
- }
- function profileFunction() {
- var xmlhttp = new XMLHttpRequest();
- xmlhttp.onreadystatechange = function () {
- if (this.readyState == 4 && this.status == 200) {
- var myObj = JSON.parse(this.responseText);
- document.getElementById("profile").innerHTML = '<li>' + 'name: ' + myObj.name; '</li>'
- }
- };
- xmlhttp.open("GET", "http://35.246.169.20:3000/profile", true);
- xmlhttp.send();
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement