ajax interview

ajax interview

手写一个简易的ajax

跨域的常用实现方式

手写一个简易的ajax    
    function ajax(url,successFn){
        const xhr = new XMLHttpRequest()
        xhr.open("GET",url,true)
        xhr.onreadystatechange = function(){
            if(xhr.readyState ===4){
            }
        }
    }
    xhr.send(null)
}
function ajax(url){
    const p = new Promise((resolve,reject)=>{
        const xhr = XMLHttpRequest()
        xhr.open('GET',url,true)
        xhr.onreaystatechange = function(){
             if(xhr.readyState ===4 ){

                if(xhr.status === 200){
                    resolve(
                        JSON.parse(xhr.responseText)
                    )
                }else if (xhr.status === 404){
                    reject(new Error)
                }
            }
        }
        xhr.send(null)
    })
}
return p


const url = 'data/test.json'
ajax(url)
.then(res=>console.log(res))
.catch(err=>console.error(err))