Ajax and FETCH apis are similar and different

ajax

Implemented with 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); }}// Set the request timeout period
    xhr.timeout = 3000;
    xhr.ontimeout = () = > {
        console.log('timeout');
    }
    // progress Progress of uploading the event report file
    xhr.upload.onprogress = p= > {
        console.log(Math.round((p.loaded / p.total) * 100) + The '%')}// Send the request
    xhr.send()
Copy the code

fetch

  1. Cookies are not included by default
  2. Error does not reject
  3. Timeout Settings are not supported
  4. AbortController is needed to abort fetch
    fetch('https://api.com', {
        method: 'GET'.credentials: 'same-origin'
    })
    .then(res= > {
        // Errors do not reject, so the request is successful
        if(response.ok) {
            return response.json();
        }
        throw new Error('Network error');
    }
    .then(json= > console.log(json))
    .catch(error= > console.log(error))
    
    
    // Set the timeout with promise
    function fetchTimeout(url, init, timeout=3000) {
        return new Promise((resolve,reject) = >{
            fetch(url, init)
            .then(resolve)
            .catch(reject);
            setTimeout(reject, timeout)
        })
    }
    
    / / suspend the 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();
Copy the code