-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter12-HTTPRequests.html
96 lines (76 loc) · 2.36 KB
/
chapter12-HTTPRequests.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<html>
<body>
<script type="text/javascript">
//The HTTP Protocol
//A simple request might look like this
// GET /files/data.txt HTTP/1.1
// Host: eloquentjavascript.net
// User-Agent: My Imaginary Browser
//A typical response
// HTTP/1.1 200 OK
// Last-Modified: Mon, 23 Jul 2007 08:41:56 GMT
// Content-Length: 40
// Content-Type: text/plain
// This is the content of the file data.txt
// The XMLHttpRequest API
// Creating a Request Object
function requestObject() {
if (window.XMLHTTPRequest)
return new XMLHttpRequest();
else if (window.ActiveXObject)
return new ActiveXObject("Msxml2.XMLHTTP");
else
throw new Error("Could not create HTTP request object.");
}
// A Simple Request
var request=requestObject();
request.open("GET","files/data.txt",false);
request.send(null);
request.responseText;
// "This is the content of the file data.txt"
request.getResponseHeader("Content-Type");
// "text/plain"
request.status;
// 200
request.statusText;
// "OK"
//Making Asynchronous Requests
request.open("GET", "files/data.txt", true);
request.send(null);
// A request object has a readyState property, indicating the state it is in. To react to changes in this status, you can set the "onreadystatechange" property to a function that is called every time the state changes.
request.open("GET", "files/data.txt", true);
request.onreadystatechange = function() {
if(request.readyState = 4)
print(request.status + " " + request.statusText);
};
request.send(null);
// Fetching XML Data
request.open("GET", "files/fruit.xml", false);
request.send(null);
request.responseXML.documentElement.childNodes.length;
//Reading JSON data
request.open("GET","files/fruit.json",true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var data = eval("(" + request.responseText + ")");
print(data["lemon"]);
}
};
request.send(null);
// A Basic Request Wrapper
function simpleHttpRequest(url, success, failure) {
var request = requestObject();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(request.readyState==4) {
if(request.status==200 || !failure)
success(request.responseText);
else if (failure)
failure(request.status, request.statusText);
}
};
request.send(null);
}
</script>
</body>
</html>