JS基础-用XMLHttpRequest实现一个ajax

//用promise进行封装
function ajax(url) {
    return new Promise(
        (resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {  //结束并有返回值状态
                    if (xhr.status === 200) {
                      resolve(xhr.responseText)
                    }else{
                      reject("失败了呢!")
                    }
                }
            }
            xhr.open("GET",url,true);
            xhr.send(null);
        }
    )
}

ajax("./data1.json").then(res=>{
  alert(`下载成功!${res}`);
}).catch(err=>{
  alert(`${err}`);
})
发布了11 篇原创文章 · 获赞 0 · 访问量 259

猜你喜欢

转载自blog.csdn.net/jinbiao8246/article/details/105386564