-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathajax1.html
76 lines (61 loc) · 1.92 KB
/
ajax1.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
76
<!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 1 - Text File</title>
</head>
<body>
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>
<script>
// Create an Even Listener
document.getElementById('button').addEventListener('click', loadText);
function loadText() {
// Create XHR Object
var xhr = new XMLHttpRequest();
// OPEN - type, url/file, async
xhr.open('GET', 'sample2.txt', true);
console.log('READYSTATE: ', xhr.readyState);
// OPTIONAL - used for loaders(like something is loading)
xhr.onprogress = function(){
console.log('READYSTATE: ', xhr.readyState);
}
xhr.onload = function() {
console.log('READYSTATE: ', xhr.readyState);
if (this.status == 200) {
// console.log(this.responseText);
document.getElementById('text').innerHTML = this.responseText;
} else if(this.status = 404) {
document.getElementById('text').innerHTML = 'Not Found';
}
}
xhr.onerror = function(){
console.log('Request Error...');
}
// If you use onreadystatechange method dont forget to check the
// readystate!
// xhr.onreadystatechange = function(){
// console.log('READYSTATE: ', xhr.readyState);
// if(this.readyState == 4 && this.status == 200){
// // console.log(this.responseText);
// }
// }
// Sends Request
xhr.send();
}
// Ready Stage Value
// 0: request not initialized
// 1: server connection established
// 2: request received
// 3: processing Request
// 4: request finished and reponse is ready
// HTTP Status
// 200: OK
// 403: Forbidden
// 404: Not Found
</script>
</body>
</html>