-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRahul_API.html
More file actions
103 lines (90 loc) · 3.15 KB
/
Rahul_API.html
File metadata and controls
103 lines (90 loc) · 3.15 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<!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">
<title>Rahul API</title>
<style>
table {
border: 1px;
}
</style>
</head>
<body>
<div>
<table border="1px">
<tr>
<th>ID</th>
<th>UserID</th>
<th>Title</th>
<th>Body</th>
</tr>
<tbody class="tableBody"></tbody>
</table>
</div>
<script>
//API Call can be done by many ways..
//1. Using XMLHttpRequest
//2. Using fetch API
//3. Using jQuery
//4. Using Axios
// Call API "https://jsonplaceholder.typicode.com/comments" using XMLHttpRequest
// var xhr = new XMLHttpRequest();
// xhr.open("GET", "https://jsonplaceholder.typicode.com/comments"); //GET is used to fetch data from server
// xhr.send();
// xhr.onreadystatechange = function () {
// if (xhr.readyState == 4 && xhr.status == 200) {
// var data = JSON.parse(xhr.responseText);
// console.log(data);
// }
// }
// Call API "https://jsonplaceholder.typicode.com/comments" using fetch API
const tableBody = document.querySelector(".tableBody");
const reqData = [];
fetch("https://jsonplaceholder.typicode.com/posts/")
.then(responce => responce.json())
.then(data => {
reqData.push(data);
tableElement(data);
})
function tableElement(data) {
data.forEach((elements) => {
tableBody.innerHTML += ` <tr onclick="clickHandler(${elements.id - 1})">
<td>${elements.id}</td>
<td>${elements.userId}</td>
<td>${elements.title}</td>
<td>${elements.body}</td>
</tr>`;
})
}
function clickHandler(index) {
console.log(reqData);
const elements = reqData[0][index];
tableBody.innerHTML = ` <tr>
<td>${elements.id}</td>
<td>${elements.userId}</td>
<td>${elements.title}</td>
<td>${elements.body}</td>
</tr>
<button onclick="window.location.reload()">Back</button>
`;
}
// Call API "https://jsonplaceholder.typicode.com/comments" using jQuery
// $.ajax({
// url: "https://jsonplaceholder.typicode.com/comments",
// success: function (data) {
// console.log(data);
// }
// });
// Call API "https://jsonplaceholder.typicode.com/comments" using Axios
// axios.get("https://jsonplaceholder.typicode.com/comments")
// .then(function (response) {
// console.log(response);
// })
// .catch(function (error) {
// console.log(error);
// });
</script>
</body>
</html>