一、回调封装AJAX
利用回调函数思想,将url和业务函数作为参数传进去;
我们只需将open的网址改为url,然后响应数据后,使用业务函数去接受这个数据并调用。
function myAjax(url,callback){
let xhr=new XMLHttpRequest()||new ActiveXObject("Microsoft.XMLHTTP")
xhr.open("GET",url,true)
xhr.send()
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
callback(xhr.responseText)
}
}
}
使用myAjax
<button onclick="load()">点我请求ajax1数据</button>
<script>
function load() {
myAjax("http://localhost:8081/ajax1", function (data) {
console.log(data)
})
}
</script>
二、promise封装AJAX
主要解决异步深层嵌套(回调地狱)的问题,它提供了简洁的API使得异步操作更加容易。
function promiseAjax(url) {
let p1 = new Promise((resolve, reject) => {
try {
let xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP")
xhr.open("GET", url, true)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(xhr.responseText)
} else if (xhr.status == 400) {
reject(xhr.responseText)
} else {
reject("not 404 found")
}
}
}
} catch (e) {
reject(xhr.responseText)
}
})
return p1
}
调用then取出正确数据
<body>
<button onclick="load()">点我请求ajax1数据</button>
<script>
function load() {
let p1 = promiseAjax("http://localhost:8081/ajax1")
console.log(p1)
p1.then((data) => {
console.log(data)
})
}
</script>
</body>