# XMLHttpRequest

The XMLHttpRequest.readyState property returns the state an XMLHttpRequest client is in. An XHR client exists in one of the following states:

Value State Description
0 UNSENT Client has been created. open() not called yet.
1 OPENED open() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
  1. xhr instance created, but open not called.
  2. open already called, but send not called.
  3. send already called and return http header and status, but not return http body.
  4. receiving http body but not completed.
  5. fully receive http body.
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./xhr.js"></script>
</head>
<body>
<h1 id="demo"></h1>
<script>
const xhr = new XMLHttpRequest();

if (xhr.readyState === 0)
console.log("0: Client has been created. open() not called yet.");

xhr.onreadystatechange = function () {
if (this.readyState === 1)
console.log("1: open() has been called.");
if (this.readyState === 2)
console.log(
"2: send() has been called, and headers and status are available."
);
if (this.readyState === 2) {
console.log(this.getAllResponseHeaders(), this.status);
}
if (this.readyState === 3)
console.log("3: Downloading; responseText holds partial data.");
if (this.readyState === 4)
console.log("4: The operation is complete.");
if (this.readyState === 4 && this.status === 200) {
myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr;
}
};
xhr.open("GET", "./json_demo.txt", true);
xhr.send();

/*
* json_demo.txt
* [
* "Google",
* "Runoob",
* "Taobao"
* ]
*/
</script>
</body>
</html>

# JSONP

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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JSONP</title>
</head>

<body>
<div id="divCustomers"></div>
<script type="text/javascript">
function callbackFunction(result, methodName) {
var html = "<ul>";
for (var i = 0; i < result.length; i++) {
html += "<li>" + result[i] + "</li>";
}
html += "</ul>";
document.getElementById("divCustomers").innerHTML = html;
}
</script>
<script
type="text/javascript"
src="https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"
></script>
</body>
</html>

<!--
https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction respose result as follow

callbackFunction(["customername1", "customername2"]) -->
Edited on