This repository was archived by the owner on May 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathapp.js
More file actions
72 lines (64 loc) · 2.05 KB
/
app.js
File metadata and controls
72 lines (64 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* eslint-disable no-console */
'use strict';
{
function getText() {
fetch('sample.txt')
.then(res => res.text())
.then(data => {
document.getElementById('output').innerHTML = data;
})
.catch(err => console.log(err));
}
function getUsers() {
fetch('users.json')
.then(res => res.json())
.then(data => {
let output = '<h2 class="mb-4">Users</h2>';
data.forEach(user => {
output += `
<ul class="list-group mb-3">
<li class="list-group-item">ID: ${user.id}</li>
<li class="list-group-item">Name: ${user.name}</li>
<li class="list-group-item">Email: ${user.email}</li>
</ul>
`;
});
document.getElementById('output').innerHTML = output;
});
}
function getPosts() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
let output = '<h2 class="mb-4">Posts</h2>';
data.forEach(post => {
output += `
<div class="card card-body mb-3">
<h3>${post.title}</h3>
<p>${post.body}</p>
</div>
`;
});
document.getElementById('output').innerHTML = output;
});
}
function addPost(e) {
e.preventDefault();
const title = document.getElementById('title').value;
const body = document.getElementById('body').value;
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-type': 'application/json',
},
body: JSON.stringify({ title, body }),
})
.then(res => res.json())
.then(data => console.log(data));
}
document.getElementById('getText').addEventListener('click', getText);
document.getElementById('getUsers').addEventListener('click', getUsers);
document.getElementById('getPosts').addEventListener('click', getPosts);
document.getElementById('addPost').addEventListener('submit', addPost);
}