手写一个简易的ajax

78 阅读1分钟
// 手写一个简易的ajax
    function ajax(url){
        const p = new Promise(resolve, reject=>{
            const xhr = new XMLHttpRequest()
            xhr.open('get','/login',true)
            xhr.onreadystatechange = function(){
                if(xhr.readyState===4){
                    if(xhr.status === 200){
                        resolve(JSON.parse(xhr.responseText))
                    }else{
                        reject(new Error('错误'))
                    }
                }
            }
            xhr.send(null)
        })
        return p
    }
    //调用
    const url = 'aa/bbb.json'
    ajax(url).then(res=>{
        console.log(res)
    }).catch(err=>{
        console.log(err)
    })