es6 promise ajax
阿新 • • 發佈:2021-06-21
promise ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>promise ajax</title>
</head>
<body>
<div id="ad">
</div>
<div></div>
<script>
const p = new Promise((resolve, reject) => {
//建立物件
const xhr = new XMLHttpRequest();
//初始化
xhr.open("GET", "http://www.example.com:88/ecmas6-11/data.json");
//傳送
xhr.send();
//繫結事件
xhr.onreadystatechange = function () {
//判斷
if (xhr.readyState === 4) {
//判斷響應碼
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(xhr.status);
}
}
}
});
p.then(
value => {
console.log(value);
},
reason => {
console.log(reason);
}
)
</script>
</body>
</html>