-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch xhr.html
More file actions
88 lines (81 loc) · 2.97 KB
/
fetch xhr.html
File metadata and controls
88 lines (81 loc) · 2.97 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="bootstrap/bootstrap.css">
<script src="bootstrap/bootstrap.bundle.js"></script>
<title>Fetch API</title>
</head>
<body>
<div class="container">
<h1 class="display-3">Fetch API Sandbox</h1>
<button class="btn btn-primary m-2" onclick="getText()">Get Text</button>
<button class="btn btn-success m-2" onclick="getJSON()">Get JSON</button>
<button class="btn btn-warning m-2" onclick="getAPI()">Get API Data</button>
<div id="root"></div>
<hr>
<form id="myForm">
<input type="text" class="form-control m-2" placeholder="Title" name="title">
<textarea placeholder="Body" class="form-control m-2" cols="30" rows="10" name="body"></textarea>
<input type="submit" class="btn btn-secondary m-2">
</form>
</div>
<script>
root = document.getElementById('root')
function getText(){
fetch('sample.txt')
.then(res => res.text())
.then(res => root.innerHTML=res)
.catch(err=> console.log(err))
.finally(console.log("finished"))
}
function getJSON(){
fetch('sample.json')
.then(res => res.json())
.then(res => root.innerHTML= JSON.stringify(res))
}
function getAPI(){
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(res => {
output = ""
for(key in res){
output += `<li>${res[key]}</li>`
}
root.innerHTML = output
})
}
myForm.onsubmit = e =>{
e.preventDefault()
fetch('https://jsonplaceholder.typicode.com/posts', {
method : 'POST',
body : JSON.stringify({
title: e.target.title.value,
body: e.target.body.value,
userId : 1
}),
headers : { 'Content-type' : 'application/json; charset=UTF-8' }
})
.then(res => res.json())
.then(res => console.log(res))
/*
xhr = new XMLHttpRequest()
xhr.open('POST','https://jsonplaceholder.typicode.com/posts')
xhr.onload = function(){
console.log(this.status)
console.log(this.response)
}
xhr.setRequestHeader('Content-type', 'application/json')
xhr.send(
JSON.stringify({
title: e.target.title.value,
body: e.target.body.value,
userId : 1
}))
*/
}
</script>
</body>
</html>