-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
97 lines (89 loc) · 2.6 KB
/
index.html
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Fetch API</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="fetchSandox.js"></script>
</head>
<body>
<button id="getText">Get Text</button>
<button id="getUsers">Get JSON</button>
<button id="getPosts">Get API Data</button>
<hr>
<div id="output"></div>
<hr>
<form id="addPost">
<div>
<input type='text' id='title' placeholder="title" />
</div>
<div>
<textarea placeholder="Body" id="body">
</textarea>
</div>
<input type="submit" />
</form>
<script>
document.getElementById('getText').addEventListener('click',getText);
document.getElementById('getUsers').addEventListener('click',getUsers);
document.getElementById('getPosts').addEventListener('click',getPosts);
document.getElementById('addPost').addEventListener('submit',addPost);
function getText() {
fetch('sample.txt')
.then((res) => res.text())
.then((data) => {
document.getElementById('output').innerHTML = data;
});
}
function getUsers() {
fetch("users.json")
.then((res) => res.json())
.then((data) => {
let output = '<h2>Users</h2>';
data.forEach(function(user){
output +=`
<ul>
<li>ID: ${user.id}</li>
<li>Name: ${user.name}</li>
<li>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>Posts</h2>';
data.forEach(function(post){
output +=`
<section>
<h2> ${post.title} </h2>
<p> ${post.body} </p>
`;
});
document.getElementById('output').innerHTML = output;
});
}
function addPost(event) {
event.preventDefault();
let title = document.getElementById('title').value;
let body = document.getElementById('body').body;
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-type': 'application/json'
},
body: JSON.stringify({title:title, body:body})
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.log(error))
}
</script>
</body>
</html>