手写简易ajax

手写简易的ajax

//手写简易ajax
function ajax(url) {
    
    
    const p = new Promise((resolve, reject) => {
    
    
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        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;
}
const url = './data/test1.json';
ajax(url)
    .then(res => console.log(res)) //fuifilled状态触发then回调
    .catch(err => console.error(err));//rejected状态会触发catch回调

猜你喜欢

转载自blog.csdn.net/Qingshan_z/article/details/119795258