Encapsulation of native ajax requests

Posted by Coronet on Sat, 26 Feb 2022 09:54:06 +0100

Encapsulation of native ajax requests

The native ajax request is divided into four steps:

1. Create request object

Determine browser compatibility issues
ie browser: window ActiveXObject
Common browser: window XMLHttpRequest

 if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

2. Call the open method

Using the open () method

3. Send request

Using the send() method

4. Judge and execute the request

Judge whether the transition readyState is equal to 4 and the status is equal to 200. If these two conditions are met, the request is successful

readyState has five possible values:

0 (uninitialized): (XMLHttpRequest) object has been created, but the open() method has not been called.
1 (load): the open() method has been called, but the request has not been sent.
2 (load completed): the request has been sent.
3 (interaction): partial response data can be received.
4 (complete): all data has been received and the connection has been closed.

status

1xx Info prompt:
100 Continue tells the client to continue sending the request, and the data transmission is not completed
101 Switching Protocols protocol conversion
2xx Successful response message:
**200 OK request - response successful
201 Created created successfully

3xx Redirection request needs to be redirected to another URL:
301 the resource requested by moved permanently has been permanently removed
303 See Other
304 Not Modified the requested resource has not been modified. Please directly use the resource cached by the client. It is not an error, it means that the cache hit, that is, the requested resource exists in the client cache

4xx Client Error:
400 Bad Request invalid request message
402 Payment Required the requested resources are not paid
403 Forbidden requested resource is not allowed to be accessed
404 Not Found the requested resource does not exist
405 Method Not Allowed the request method is not allowed by the server
414 request URI too long the URI of the request is too large to be resolved

5xx Server Error

500 Internal Server Error
503 Service Unavailable server was attacked
505 HTTP Version Not Supported server version is too low

Synchronous and asynchronous request encapsulation and usage of get and post of native ajax

// get synchronization
/**
 * 
 * @param {*} url Path to the request file
 * @param {*} parms url The format of the parameters passed later is as follows: name = Zhang & age = 18
 * @param {*} success After the request is successful, the success function is called.
 * @param {*} error After the request fails, the error function is called.
 */
function getSync(url, parms, success, error) {
    if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xhr.open('get', url + '?' + parms, false);
    xhr.send();
    if (xhr.readyState == 4 && xhr.status == 200) {
        success(xhr);
    } else {
        error('request was aborted');
    }
}

// Asynchrony of get
function getAsync(url, parms, success, error) {
    if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xhr.open('get', url + '?' + parms, true);
    xhr.send();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                success(xhr);
            } else {
                error('request was aborted');
            }
        }
    }
}

// post synchronization
function postSync(url, parms, success, error) {
    if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    xhr.open('post', url, false);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(parms);
    if (xhr.readyState == 4 && xhr.status == 200) {
        success(xhr);
    } else {
        error('request was aborted');
    }
}

// post asynchronous
function postAsync(url, parms, success, error) {
    if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }

    xhr.open('post', url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(parms);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                success(xhr);
            } else {
                error('request was aborted');
            }
        }
    }
}


/*  // Encapsulation call test
    getAsync('test.php', '', suc, err);

    function suc(msg) {
        console.log(msg.responseText);
    }

    function err(tip) {
        console.log(tip);
    } */


//     encapsulation
//     get synchronization getSync
//     Asynchronous getAsync for get
//     post sync
//     post Async

Topics: Javascript Front-end Ajax server