js 实现 ajax,Promise + js 实现 ajax

// JS 实现ajax

function ajax(url){
    const xhr =new XMLHttpRequest()
    xhr.open("GET",url,false)
    xhr.onreadystatechange=function(){
        if(xhr.readyState===4){
            if(xhr.status===200){
                console.log(JSON.parse(xhr.responseText))
            }else{
                console.log("其他情况")
            }
        }
    }
    xhr.send(null)
}

//随便一个请求路径为例

ajax("https://bolt.shaoziketang.com/api/search/keywords?client=3")
//Promise 应用于 ajax

function ajax(url){
    const p = new Promise((resolve,reject)=>{
        const xhr =new XMLHttpRequest()
        xhr.open("GET",url,false)
        xhr.onreadystatechange=function(){
            if(xhr.readyState===4){
                if(xhr.status===200){
                    resolve(JSON.parse(xhr.responseText))
                }else if(xhr.status===404){
                    reject(new Error("404 not found")) //抛出错误
                }
            }
        }
        xhr.send(null)
    })
    return p
}

ajax("https://bolt.shaoziketang.com/api/search/keywords?client=3").then(data=>{
    console.log(data)
}).catch(ex=>console.error(ex))

 


版权声明:本文为Supercaojh原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>