<script>
// 封装一个函数sendAJAX发送GET请求,参数为url,放回结果为Promise对象
function sendAJAX(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open("GET", url);
xhr.send();
//处理结果
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
//判断成功
if (xhr.status >= 200 && xhr.status < 300) {
//成功的结果
resolve(xhr.response);
}
//失败的结果
reject(xhr.status);
}
};
});
}
sendAJAX("http://api.apiopen.top/getJoke").then(
(value) => {
console.log(value);
},
(reason) => {
console.warn(reason);
}
);
</script>
723_promise_ajax封装练习
- 本文链接: http://lzkpersonal.com.cn/2023/07/23/723-promise-ajax封装练习/
- 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!