//ajax的回调函数的封装,建议不使用回调函数处理异步问题
let btn = document.querySelector('button')
btn.addEventListener('click', () => {
ajax('get', '/data', function (res) {
alert(res)
})
})
function ajax(method = 'get', url = '/data', fun) {
const xhr = new XMLHttpRequest()
xhr.open(method, url)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
fun(xhr.responseText)
}
}
}
//promise
let btn = document.querySelector('button')
btn.addEventListener('click', () => {
ajax('get', '/data').then(res => {
alert(res)
})
})
function ajax(method = 'get', url = '/data') {
return new Promise((resolve) => {
const xhr = new XMLHttpRequest()
xhr.open(method, url)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText)
}
}
})
}