Skip to content

Commit

Permalink
added example of fetch api
Browse files Browse the repository at this point in the history
  • Loading branch information
chadsmith12 committed May 15, 2018
1 parent eba28c5 commit a27772a
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 0 deletions.
57 changes: 57 additions & 0 deletions fetch-api/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Fetch API Examples
* Example file of using the fetch API get data like text, json, and from an api.
*/

const textBtn = document.getElementById("getText");
const jsonBtn = document.getElementById("getJson");
const apiBtn = document.getElementById("getApi");
const output = document.getElementById("output");

textBtn.addEventListener('click', getText);
jsonBtn.addEventListener('click', getJson);
apiBtn.addEventListener('click', getApiData);


function getText() {
fetch('test.txt').then(function(response) {
return response.text();
}).then(function(data){
output.innerHTML = data;
}).catch(function(err){
output.innerHTML = data;
});
}

function getJson() {
fetch('test.json').then(function(response) {
return response.json();
}).then(function(data) {
output.innerHTML = `
<ul>
<li>${data.firstName}</li>
<li>${data.lastName}</li>
<li>${data.age}</li>
</ul>
`;
}).catch(function(err){
output.innerHTML = data;
});
}

function getApiData() {
fetch('https://api.github.com/users').then(function(response) {
return response.json();
}).then(function(data) {
data.forEach(element => {
output.innerHTML += `
<ul>
<li>${element.login}</li>
</ul>
`;
});

}).catch(function(err){
output.innerHTML = err;
});
}
22 changes: 22 additions & 0 deletions fetch-api/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" />
<title>Fetch API</title>
</head>
<body>
<div class="container">
<h1>Fetch API</h1>
<button type="button" id="getText">Get Text</button>
<button type="button" id="getJson">Get JSON</button>
<button type="button" id="getApi">Get Data From API</button>
<br><br>
<div id="output"></div>
</div>

<script src="app.js"></script>
</body>
</html>
5 changes: 5 additions & 0 deletions fetch-api/test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"firstName": "Chad",
"lastName": "Smith",
"age": "28"
}
1 change: 1 addition & 0 deletions fetch-api/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Hello world, From test.txt.

0 comments on commit a27772a

Please sign in to comment.