用promise封装AJAX的代码如下:
封装代码:
function myaxios(url) {
var p1 = new Promise(function (n1, n2) {
var xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP")
xhr.open("GET", url, true)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
n1(xhr.responseText)
} else if (xhr.readyState == 4 && xhr.status == 404) {
n2(xhr.responseText)
}
}
})
return p1
}
调用时的方法:
<button onclick="fn()">ajax请求</button>
<script>
function fn() {
var url = "http://192.168.0.114:8081/ajax1" //要请求的目标网址
myaxios(url).then((res) => {
console.log(res);
})
}
</script>