forked from learning-zone/javascript-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathajax.html
47 lines (46 loc) · 1.49 KB
/
ajax.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
<!DOCTYPE html>
<html>
<head>
<title>AJAX Request in JavaScript</title>
</head>
<body>
<h3>AJAX - Send a Request To a Server</h3>
<button id="ajaxButton" type="button">Make a request</button>
<div id="result"></div>
</body>
<script>
/**
*
* AJAX - Asynchronous JavaScript and XML
*
* readyState() Values:-
*
* a) 0 (uninitialized) or (request not initialized)
* b) 1 (loading) or (server connection established)
* c) 2 (loaded) or (request received)
* d) 3 (interactive) or (processing request)
* e) 4 (complete) or (request finished and response is ready)
*/
(function() {
var xhr;
document.getElementById('ajaxButton').addEventListener('click', makeRequest);
function makeRequest() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = '<pre>' + this.responseText + '</pre>';
}
};
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true); //this makes asynchronous true or false
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send();
}
})();
</script>
</html>