-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavascript_api_json.html
More file actions
78 lines (60 loc) · 1.98 KB
/
javascript_api_json.html
File metadata and controls
78 lines (60 loc) · 1.98 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
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title> Pure Java JSON data - fetch API </title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/0.10.1/fetch.js"></script>
</head>
<body>
<div class="container bg-dark text-light p-4 mt-1 rounded">
<h1> PURE JAVASCRIPT AND API </h1>
<button class="btn btn-success text-center" onclick="search();"> Fetch API Data</button>
<hr />
<div id="users"></div>
</div>
<script>
function search() {
// the URLData the json file..
var UrlData = "https://jsonplaceholder.typicode.com/users";
fetch(UrlData).
then(function (response) {
// This fpr response.json() returns a json string,
// returning it will convert it
// to a pure JavaScript
// object for the next then's callback
return response.json();
}).
then(function (users) {
// users is a JavaScript object here
displayUsersAsATable(users);
}).
catch(function (error) {
console.log('Error: ' + error.message);
});
}
function displayUsersAsATable(users) {
// users is a JavaScript object
// empty the div that contains the results
var usersDiv = document.querySelector("#users");
usersDiv.innerHTML = "";
// creates and populate the table with users
var table = document.createElement("table");
// iterate on the array of users
users.forEach(function (currentUser) {
// creates a row
var row = table.insertRow();
// insert cells in the row
// This is for the name
var nameCell = row.insertCell();
nameCell.innerHTML = " Name: " + currentUser.name;
// This is for the name
var cityCell = row.insertCell();
cityCell.innerHTML = " City: " + currentUser.address.city;
});
// adds the table to the div
usersDiv.appendChild(table);
}
</script>
</body>
</html>