• XMLHttpRequest is a client-side API that provides the ability to transfer data from the client to the server. It can be used by sending simple or fetching data to a URL without refreshing the page and is often used for AJAX requests. Supports XML, HTTP, FILE, and FTP protocols.

Here’s a simple example:

const xhr = new XMLHttpRequest();
xhr.open("GET"."http://example.com".false);
xhr.send();Copy the code

In fact, when we develop, we need to receive the data after the request is successful, as follows:

  • Note here that onReadyStatechange must be declared before the open method is called. Otherwise, the response event cannot be reset after the request is sent
const xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
        console.log('Request successful')
        console.log(this.response)
    } else if (this.readyState === 1) {
        console.log('On request')}else {
        console.log('Request failed')
    }
}

xhr.open('GET'.'https://www.baidu.com'.false);
xhr.send();Copy the code

  • Now, let’s play a little bit more fun (asynchronous vs. synchronous)

Source code is as follows:

console.log(1)

const xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
    console.log(2)
    if (this.readyState === 4 && this.status === 200) {
        console.log('Request successful')}else if (this.readyState === 1) {
        console.log('On request')}else {
        console.log('Request failed')
    }
}

xhr.open('GET'.'https://www.baidu.com'.false); // falsetotrue
xhr.send();

console.log(3)Copy the code

The results are as follows:

When we change false to true in the code above. The results are as follows:

What’s going on? The third parameter of the XMLHttprequest open method controls whether it is asynchronous or not. We initially set it to false, indicating that the command is executing synchronously and blocking the code.

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help, check xhr.spec.whatwg.org/.

Executing synchronized code will clog up the code and affect the user experience. When we change false to true later, it’s also obvious that after printing 1, we print 3 immediately, unlike the first time, when we waited for 2 to print 3.

  • Wrap AJAX as a Promise object

Here, I’m going to mimic how Axios works:

axios.get('http://example.com');
axios.post('http://example.com');Copy the code

Axios class library

class Axios {
    get(url, data = {}) {
        return this.XMLHttpRequestObject('GET', url, data);
    }
    post(url, data = {}) {
        return this.XMLHttpRequestObject('POST', url, data);
    }
    XMLHttpRequestObject(method, url, data) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (this.readyState === 4 && this.status === 200) {
                    console.log('Request successful')
                    resolve(this.response)
                } else if (this.readyState === 1) {
                    console.warn('On request')}else if (this.readyState === 4) {
                    console.error('Request failed')
                    reject('Request failed')}}if (method === 'GET'Xhr.open (method, url,true);
            xhr.send(data);
            returnxhr; }}})Copy the code

Call Axios

const axios = new Axios(); // Create a new Axios instance console.log(await axios.get('https://www.example.com'))
console.log('All done')Copy the code

PS: The above is the case without IE, I will fill in the hole later