Repository navigation
Expand file tree
/
Copy path2_JSON.html
More file actions
74 lines (67 loc) · 2.08 KB
/
Copy path2_JSON.html
File metadata and controls
74 lines (67 loc) · 2.08 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
<!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" />
<title>AJAX Sandbox</title>
</head>
<body>
<div class="container">
<button id="button1">Get Customer</button>
<button id="button2">Get Customers</button>
<h1>Customer</h1>
<div id="customer"></div>
<br /><br />
<h1>Customers</h1>
<div id="customers"></div>
</div>
</body>
<script>
// Event Listeners for the buttons
document.querySelector("#button1").addEventListener("click", loadCustomer);
function loadCustomer() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "data/customer.json", true);
xhr.send();
xhr.onload = function() {
if (this.status === 200) {
console.log(this.responseText);
const customer = JSON.parse(this.responseText);
console.log(customer);
const output = `
<ul>
<li>ID : ${customer.id}</li>
<li>Name: ${customer.name}</li>
<li>Phone: ${customer.phone}</li>
</ul>
`;
document.querySelector("#customer").innerHTML = output;
}
};
}
document.querySelector("#button2").addEventListener("click", loadCustomers);
function loadCustomers() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "customers.json", true);
xhr.send();
xhr.onload = function() {
if (this.status === 200) {
const customers = JSON.parse(this.responseText);
// console.log(customers);
let output = "";
customers.forEach(customer => {
output += `
<ul>
<li>ID : ${customer.id}</li>
<li>Name: ${customer.name}</li>
<li>Phone: ${customer.phone}</li>
</ul>
`;
document.querySelector("#customers").innerHTML = output;
});
}
};
}
</script>
</html>