-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxhr-promise.html
43 lines (39 loc) · 1.2 KB
/
xhr-promise.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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AMD Promise Tests</title>
</head>
<body>
<script src="jquery.js"></script>
<script src="promise.js"></script>
<script>
var $parent = $("body"); // 获取<ul>节点。<li>的父节点
function getURL(URL) {
return new Promise(function (resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', URL, true);
req.onload = function () {
if (req.status === 200) {
resolve(req.responseText);
} else {
reject(new Error(req.statusText));
}
};
req.onerror = function () {
reject(new Error(req.statusText));
};
req.send();
});
}
// 运行示例
var URL = "http://httpbin.org/get";
getURL(URL).then(function onFulfilled(value) {
$parent.append($("<div></div>").text(value));
console.log(value);
}).catch(function onRejected(error) {
console.error(error);
});
</script>
</body>
</html>