浏览器请求 - ajax和fetch

203 阅读1分钟

ajax 和 fetch API 异同

ajax

通过XMLHttpRequest实现

    let xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://api.com');
    xhr.onreadystatechange = function() {
        if(xhr.readyState !== 4) return;
        
        if(xhr.status === 200) {
            console.log(xhr.responseText);
        } else {
            console.log('error', xhr.status);
        }
    }
    // 设置请求超时时间
    xhr.timeout = 3000;
    xhr.ontimeout = () => {
        console.log('timeout');
    }
    // progress事件报告文件上传进度
    xhr.upload.onprogress = p => {
        console.log(Math.round((p.loaded / p.total) * 100) + '%')
    }
    // 发送请求
    xhr.send()

fetch

  1. 默认不带cookie
  2. 错误不会reject
  3. 不支持超时设置
  4. 需要借用AbortController中止fetch
    fetch('https://api.com', {
        method: 'GET',
        credentials: 'same-origin'
    })
    .then(res => {
        // 错误不会reject,所以判断是否请求成功
        if(response.ok) {
            return response.json();
        }
        throw new Error('Network error');
    }
    .then(json => console.log(json))
    .catch(error => console.log(error))
    
    
    // 通过promise设置超时
    function fetchTimeout(url, init, timeout=3000) {
        return new Promise((resolve,reject)=>{
            fetch(url, init)
            .then(resolve)
            .catch(reject);
            setTimeout(reject, timeout)
        })
    }
    
    // 中止fetch
    const controller = new AbortController();
    fetch(url, options)
    .then(response => response.json())
    .then(json => console.log(json))
    .catch(error => console.error('Error:', error));
    
    controller.abort();