-
Notifications
You must be signed in to change notification settings - Fork 0
/
ajax2.html
75 lines (65 loc) · 2.2 KB
/
ajax2.html
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
<!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>Document</title>
<!-- <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script> -->
</head>
<body>
<button id='button1'>Get USER</button>
<button id='button2'>Get USERS</button> <br /><br />
<h1>user</h1>
<div id='user'></div>
<br /><br />
<h1>users</h1>
<div id='users'></div>
<script>
document.getElementById('button1').addEventListener('click', loadUser);
document.getElementById('button2').addEventListener('click', loadUsers);
function loadUser() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'user.json', true);
xhr.onload = function() {
if (this.status == 200) {
// json . parse to getting json property of the object
var user = JSON.parse(this.responseText);
console.log(this.responseText);
console.log(user.name);
console.log(user.id);
console.log(user.email);
var output = '';
output +=
'<ul>' +
'<li>ID: ' + user.id + '</li>' +
'<li>ID: ' + user.name + '</li>' +
'<li>ID: ' + user.email + '</li>' +
'</ul>';
document.getElementById('user').innerHTML = output;
}
}
xhr.send();
}
function loadUsers() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json', true);
xhr.onload = function() {
if (this.status == 200) {
var users = JSON.parse(this.responseText);
var output = '';
for(var i in users) {
output += '<ul>' +
'<li>Id: ' +users[i].id+ '</li>' +
'<li>name: ' +users[i].name+ '</li>' +
'<li>Email: ' +users[i].email+ '</li>' +
'</ul>';
}
document.getElementById('users').innerHTML = output;
}
}
xhr.send();
}
</script>
</body>
</html>