Ajax learning notes

Ajax

It is a set of methods provided by the browser, which can update the data without refreshing the page (i.e. locally update the data in the page in the process of browsing the web page), and improve the user's experience of browsing the website application.
Note: ajax technology needs to run in the website environment and take effect. It should be able to open the page in the form of localhost domain name.

Ajax application scenario

1. Pull up the page to load more data
2. The list data has no refresh page
3. Form item leaving focus data verification
4. Drop down list of prompt text in search box

Ajax operation principle and Implementation

AJAX is equivalent to the agent of the browser sending request and receiving response. Ajax helps the browser send request and receive the data from the server to the client. When it receives the response data, it uses dom method to add the data content sent by the server to the page, so as to refresh the data while browsing the page, so as to improve the user experience.

1. Getting started with Ajax

//app.js
app.get('/first', (req, res) => {
    res.send('hello ajax');
});

//In the < script > tag of html file
        //1. Create ajax objects
        var xhr = new XMLHttpRequest();
        //2. Tell the ajax object where and how to send the request
        //Open (request mode, request address)
        xhr.open('get', 'http://localhost:8888/first');
        //3. Send request
        xhr.send();
        //4. Get the data that the server responds to the client
        //The request response time is uncertain, so it is impossible to get the data directly after send ing
        //Here, use onload to listen for xhr events
        xhr.onload = function() {
            //xhr.responseText saves the data returned by the server to the client
            console.log(xhr.responseText);
        }

2. Data type of server response

In the actual development, the server side will take JSON object as the format of response data in most cases. When the client gets the response data, it should splice the JSON data and HTML string, and then display the splicing results in the page.

However, in the process of http request and response, whether the request parameters or response contents are object types, they will eventually be converted into object strings for transmission.

So we finally need to use json for the returned data Parse() converts json strings into json objects.

Ajax error handling

  1. The network is unblocked, the server can receive the request, and the result returned by the server is not the expected result.
    The status code returned by the server can be judged and processed separately. xhr.status get http status code

  2. If the network is unblocked and the server does not receive the request, the 404 status code is returned.
    Check if the requested address is wrong.

  3. The network is unblocked, the server can receive the request, and the server returns 500 status code.
    Server side error, find back-end programmers to communicate.

  4. The network is interrupted and the request cannot be sent to the server.
    The onerror event under the xhr object will be triggered, and the error will be handled in the onerror event handling function.

Encapsulating ajax functions

1. Encapsulate the repeatedly executed code:
(1) Creating ajax objects
(2) Configuring ajax objects
(3) Send request
(4) To listen to the onload event under the xhr object, you need to judge the http status code and the response data type

2. Request parameters
(1) Location of request parameters: pass the request parameters to the ajax function, and place the request parameters in different locations within the function according to different request methods (get is placed after the request address, and post is placed in the send method)
(2) Format of request parameter transfer: it is more convenient for users to transfer data in json format, and string splicing and conversion are carried out inside ajax
(3) Respond to the corresponding data format according to the request parameter type

3. Set the default values of some parameters when calling ajax functions

//ajax function encapsulation
function ajax(options) {
    //Store defaults
    var defaults = {
        type: 'get',
        url: '',
        data: {},
        header: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function() {},
        error: function() {}
    }

    //Object overrides affect the original object
    Object.assign(defaults, options);
    //1. Create ajax objects
    var xhr = new XMLHttpRequest();

    //Variables of splicing request parameters
    var params = '';
    for (var attr in defaults.data) {
        params += attr + "=" + defaults.data[attr] + '&';
    }
    //Intercept the & character at the end of the parameter
    params = params.substr(0, params.length - 1);

    //Judge the request parameters. If the request method is get
    if (defaults.type == 'get') {
        defaults.url = defaults.url + '?' + params;
    }

    //2. Configure ajax objects (request method and request address cannot be determined)
    xhr.open(defaults.type, defaults.url);

    //3. Send request
    //Judge the request parameters. If the request method is post
    if (defaults.type == 'post') {
        //The type of request parameter that the user wants to pass to the server
        var contentType = defaults.header['Content-Type'];
        //Sets the type of request parameter format
        xhr.setRequestHeader('Content-Type', contentType);
        //Judge the type of request parameters that the user wants to pass to the server
        if (contentType == 'application/json') {
            //Pass json format parameters to the server
            xhr.send(JSON.stringify(defaults.data));
        } else {
            //Pass common type request parameters to the server
            xhr.send(params);
        }
    } else {
        xhr.send();
    }

    //4. Listen for onload event under xhr object
    //Triggered when the xhr object receives the response data
    xhr.onload = function() {
        //Gets the data type in the response header
        var dataType = xhr.getResponseHeader('Content-Type');
        //Data returned by the server
        var responseText = xhr.responseText;

        //If the response type contains json
        if (dataType.includes('application/json')) {
            //Convert string to json format object
            responseText = JSON.parse(responseText);
        }

        if (xhr.status == 200) {
            //Request succeeded
            defaults.success(responseText, xhr);
        } else {
            //request was aborted
            //xhr.responseText passes an error message at this time
            defaults.error(responseText, xhr);
        }
    }
}

//ajax function usage
ajax({
    type: 'get', //Request mode
    url: 'http://localhost:8888/responseData ', / / request address
    data: {
        name: 'zhangsan',
        age: 20
    },
    header: {
        'Content-Type': 'application/json'
    },
    success: function(data) {
        console.log('success function');
        console.log(data);
    },
    error: function(data, xhr) {
        console.log('Here is error function' + data);
        console.log(xhr);
    }
});

Keywords: Ajax

Added by nsr500rossi on Wed, 02 Feb 2022 03:16:18 +0200