<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="container">
<button class="btn">点击发送Ajax</button>
</div>
<script>
const btn = document.querySelector(".btn");
btn.addEventListener("click", function () {
const p = new Promise((resolve, reject) => {
const x = new XMLHttpRequest();
x.open("GET", "https://api.apiopen.top/getJoke");
x.send();
x.onreadystatechange = function () {
if (x.readyState === 4) {
if (x.status >= 200 && x.status < 300) {
resolve(x.response);
} else {
reject(x.status);
}
}
};
});
p.then(
(value) => {
console.log(value)
},
(reason) => {
console.log(reason);
}
);
});
</script>
</body>
</html>