Ajax - native JS implements Ajax requests

Posted by bengaltgrs on Mon, 27 Dec 2021 23:02:59 +0100

1, The core of Ajax: XMLHttpRequest

Concept: XMLHttpRequest is a built-in constructor in the browser (belonging to the category of BOM and DOM) to create objects
Function: used to initiate Ajax requests is the core principle of Ajax

1. Send the request using XMLHttpRequest

Parsing ajax requests

axios({
    url:'Request address',
    method:'Request mode',
    //Query parameters
    //Request body
}).then(function(res){})

2. XMLHttpRequest must have a request address and request method

// 1. Create an XMLHttpRequset instance object
let xhr = new XMLHttpRequest();

// 2. Set the request method and address for the instance object
// xhr.open('request method ',' request address');
xhr.open('get', 'http://www.liulongbin.top:3006/api/get');

// 3. Send request
xhr.send();

// 4. Get the result of the request (returned data)
xhr.onload = function() {
    console.log(xhr.response);
}

2, XMLHttpRequest implements the get request

        // 1. Create an XMLHttpRequset instance object
        let xhr = new XMLHttpRequest();
        // 2. Set the request method and address for the instance object
        // xhr.open('request method ',' request address');
        xhr.open('get', 'http://www.liulongbin.top:3006/api/get?aa=11&&bb=22');
        // 3. Send request
        xhr.send();
        // 4. Get the result of the request (returned data)
        xhr.onload = function() {
            console.log(xhr.response);
        }

Pay attention to the implementation summary

a) View the results returned by the server XHR Onload may not be written, but it is recommended to add
b) If onload is set, the code in the onload event will be executed only when the server returns data
c)onload can be written after the instance object
d) The send method must be set after the open() method
e) Query parameters can also be set when the native JS sends a get request. The query parameters are directly spliced and written behind the address? aa=11&&bb=22
f) If the query parameter is in object format, how to splice it on the url address? Solution: traverse the object and get the key and value

let params = {
        uname: 'Zhang San',
        age: '23',
        myheight: '180'
    }
    // Target format: uname = Zhang San & age = 23 & myheight = 180

Solution: traverse the object to get the key and value:

let arr = [];
for (key in params) {
    // Save each key value pair in the array
    // console.log(key + '=' + params[key]);
    arr.push(key + '=' + params[key])
};
let str = arr.join('&');
console.log(str);
// Just add STR after the url address, 'url address' + str

3, XMLHttpRequest implements the post request

// 1. Create an XMLHttpRequset instance object
let xhr = new XMLHttpRequest();
// 2. Set the request method and address for the instance object
// xhr.open('request method ',' request address');
xhr.open('post', 'http://www.liulongbin.top:3006/api/post');
//--------------------------------------------------------------------
//Set the request body type post exclusive (must be added). Take setting the allocation/x-www-form-urlencaded format as an example
xhr.setRequestHeader('content-type', 'allocation/x-www-form-urlencaded');
// 3. Send request
xhr.send('uname=abc&pwd=123');
//--------------------------------------------------------------------
// 4. Get the result of the request (returned data)
xhr.onload = function() {
    console.log(xhr.response);
}

Note Implementation Summary:

--Same as get--
a) view the results returned by the server XHR Onload may not be written, but it is recommended to add
b) if onload is set, the code in onload event will be executed only when the server returns data
c)onload can be written after the instance object
D) the send() method must be set after the open() method
--Different from get--
e) adding the request body is not splicing after the url
f) if the request body data is required, set the request body data in the send() method (be sure to set the request body format)
Uname = ABC & PWD = 123 the corresponding request body format is allocation/x-www-form-urlencaded
The format of the request body corresponding to the request body with a split line is multipart / form data
uname=abc newline pwd=123 the corresponding format is text/plain

You can also traverse the object like get, convert the format and put it into send

let params = {
    uname: 'Zhang San',
    age: '23',
    myheight: '180'
};
// Target format: uname = Zhang San & age = 23 & myheight = 180

Solution: traverse the object and get the key and value

let arr = [];
for (key in params) {
    // Save each key value pair in the array
    // console.log(key + '=' + params[key]);
    arr.push(key + '=' + params[key])
};
let str = arr.join('&');
console.log(str);
// Just add str to send(). send(str)

4, Encapsulate your own Ajax

function myAjax(opt) {
    let xhr = new XMLHttpRequest();
    // Query parameter construction part---------------------------
    // Convert the query parameters from object to string and splice them on the address
    if (opt.params) {
        // The user has set query parameters
        let obj = opt.params;
        let ary = [];
        for (key in obj) {
            ary.push(key + '=' + obj[key])
        }
        let url_str = ary.join('&');
        //Query type and address section------------------------------
        xhr.open(opt.method, opt.url + '?' + url_str);
    } else {
        // The user has not set query parameters
        // Query type and address part ---------------------------
        xhr.open(opt.method, opt.url);
    }
    //Send-------------------------------------------
    // Judge whether the user has set the request body
    if (opt.data) {
        // With request body, XHR Send (request body data);
        // Send request body data according to request body type XHR Send (request body data);
        if (opt.data instanceof FormData) {
            //If it is data in FormData format
            //Edit request body format
            // xhr.setRequestHeader('content-type', 'multipart/form-data')
            xhr.send(opt.data);



            // Callback function construction part-------------------------------
            xhr.onload = function() {
                // console.log(this.response)
                opt.success(JSON.parse(this.response));
            };



            return;
        }
        if (opt.data instanceof Object) {
            //If it is Object format data
            let obj = opt.data;
            let ary = [];
            for (key in obj) {
                ary.push(key + '=' + obj[key])
            }
            let data_str = ary.join('&');

            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
            xhr.send(data_str);



            // Callback function construction part-------------------------------
            xhr.onload = function() {
                // console.log(this.response)
                opt.success(JSON.parse(this.response));
            };


            return;
        }
        // console.log(opt.url)
    } else {
        // No request body
        //Send an ajax request without a request body
        xhr.send();
        // console.log(opt.url)


        // Callback function construction part-------------------------------
        xhr.onload = function() {
            // console.log(this.response)
            opt.success(JSON.parse(this.response));
        };
    }
}

Topics: Javascript Front-end Ajax