<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Promise异步请求</title>
</head>
<body>
<script type="text/javascript">
// promise
var url = 'http://localhost/hello.php'
function getData (url) {
let promise = new Promise((resolve,reject) => {
// 创建ajax
// 1. 创建 XMLHttp
var xmlHttp = new XMLHttpRequest()
// 2. 监听发送
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
// 成功
resolve(xmlHttp.responseText)
} else {
// 失败
reject('请求失败')
}
}
}
// 3. 获取url
xmlHttp.open("GET",url)
xmlHttp.send()
})
return promise
}
getData(url).then((res) => {
console.log(res)
}).catch((e) => {
console.log(e)
})
</script>
</body>
</html>
简单封装的Promise异步请求
猜你喜欢
转载自blog.csdn.net/qq_40411946/article/details/89842145
今日推荐
周排行