Skip to content

Commit 5077a05

Browse files
committed
added fetch example
1 parent dc13bfe commit 5077a05

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
2+
.DS_Store

fetch/index.html

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<script src="script.js">
6+
</script>
7+
<title>Fetch Examples</title>
8+
</head>
9+
10+
<body>
11+
<input type="button" value="Fetch JSON" onClick="fetchJSON();">
12+
<input type="button" value="Fetch Text" onClick="fetchText();">
13+
<div id="result"></div>
14+
</body>
15+
16+
</html>

fetch/script.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
function fetchJSON() {
3+
// make the HTTP/HTTPS call:
4+
fetch('https://dweet.io/get/dweets/for/my-thing-name')
5+
.then(response => response.json()) // convert response to JSON
6+
.then(data => getResponse(JSON.stringify(data))) // get the body of the response
7+
.catch(error => getResponse(error));// if there is an error
8+
}
9+
10+
function fetchText() {
11+
// parameters for the HTTP/S call
12+
let params = {
13+
mode: 'cors', // if you need to turn off CORS, use no-cors
14+
headers: { // any HTTP headers you want can go here
15+
'accept': 'application/text'
16+
}
17+
}
18+
// make the HTTP/S call:
19+
fetch('https://httpbin.org/encoding/utf8', params)
20+
.then(response => response.text()) // convert response to text
21+
.then(data => getResponse(data)) // get the body of the response
22+
.catch(error => getResponse(error));// if there is an error
23+
}
24+
25+
// function to call when you've got something to display:
26+
function getResponse(data) {
27+
document.getElementById('result').innerHTML = data;
28+
}

0 commit comments

Comments
 (0)