手写-封装Ajax函数

51 阅读1分钟

function itheimaAxios({ url, method}) { // 1. 外面需要Promise对象, 所以创建一个并返回 return new Promise((resolve, reject) => { // 2. 解构配置对象参数使用 let xhr = new XMLHttpRequest()

    xhr.open(method, url)
    xhr.send()
    xhr.addEventListener('load', function () {
        if(xhr.status >= 200 && xhr.status<400){
            let result = JSON.parse(xhr.response)
            resolve(result)

        } else {
            reject({message: xhr.response})
        }
    })
})

}

// 测试 itheimaAxios({ url: 'ajax-api.itheima.net/api/provinc…', method: 'GET' }).then(res => { console.log(res) }).catch(err => { console.error(err) })

// promise的作用在于改写原来需要回调函数才实现的异步操作。