node primary ---- ajax sending request and response - use of ajax in jQuery

Posted by onedumbcoder on Wed, 08 Sep 2021 00:09:26 +0200

Introduction to AJAX:

        AJAX, namely asynchronous JavaScript and XML technology, is a set of browser-side network development technology integrating many technologies.

        In short, AJAX is to use JavaScript code to send network requests and process responses. There is a browser, that is, a client implementation.

        ajax technology can interact with the server without refreshing the page. It can only send and retrieve the necessary data to the server, and use js to process the response on the client. The data exchanged is greatly reduced, and the response of the server is more rapid. The data processing work is put on the client, which reduces the load of the web server.

         Features: asynchronous request, local refresh

        Asynchronous means that after sending data, the next data packet is sent directly without waiting for a response

AJAX writing steps:

1. Creating AJAX objects

2. Set request path and request mode

3. Bind the processing function that listens to the status change. The response data can be obtained in the processing function

4. Send request

Note, however, that creating ajax objects has browser compatibility issues:

function createAjax() {
    var ajax;
    try {       // Non IE 
        ajax = new XMLHttpRequest();
    }
    catch (e) { // IE
        ajax = new ActiveXObject('Microsoft.XMLHTTP');
    }
    return ajax;
}

Response processing and response process:

        Response processing is that the server responds to the data of the client and performs different processing according to the status code and the status information of ajax objects.

        ajax objects have four properties:

1. readyState: there are 5 states, 0-4, and each value represents a different meaning:

        0: initialization, ajax object has not completed initialization

        1: After loading, the ajax object starts sending the request

        2: After loading, the request of ajax object is sent

        3: After parsing, the ajax object starts reading the server's response

        4: When finished, the ajax response to the system read server ends

2. Status indicates the HTTP status code of the response:

        200: successful

        302: redirection

        404: resource not found

        500: server error

3. responseText gets the response data in string form

4. rersponseXML gets the response data in XML form

        We can know that the processing function of state change is generally processed when readyState==4 and status==200.

Send get request using AJAX

Front end js code:

<script>
    let obtn = document.getElementById("obtn");
    let odiv = document.getElementById("odiv");

    obtn.onclick = () => {

        //Send ajax request
        // 1. Create AJAX objects;
        let ajax = new XMLHttpRequest();

        // 2. Set request path, request mode, etc; Ajax.open (request mode, path)
        ajax.open('GET', '/get_data');
        // 3. Bind the processing function for monitoring the change of state, and the response data can be obtained in the processing function;
        ajax.onreadystatechange = ()=>{
            // Get the data from the response
            if(ajax.readyState===4&& ajax.status===200){
                console.log(ajax.readyState);
                console.log(ajax.responseText);
                // After the data is requested, the data can be updated to the page
                odiv.innerHTML = ajax.responseText;
            }
        };
        // 4. Send request.
        ajax.send()
    }
</script>

Server code:

else if(requestUrl=== "/get_data"){       //Or write it as: / get_data.*/.test(requestUrl)
    response.setHeader("Content-type","text/html;charset=utf-8");
    response.write("This data is from the server...");
    response.end();
}

Avoid caching:

         In order to ensure that the information we read is up-to-date, we need to disable its caching function. The solution is as follows

  • Add a random number after the URL: Math.random().

  • Add the time after the URL: new Date().getTime().

  • Add AJAX. Setrequestheader ('cache control ',' no cache ') before sending the request using AJAX.

ajax.open( ..... );
ajax.setRequestHeader('Cache-Control', 'no-cache');
ajax.send();

Send post request using AJAX

Front end code:

<script>
    let obtn = document.getElementById("obtn");
    let odiv = document.getElementById("odiv");
    obtn.onclick = () => {
        let username = document.getElementById("username").value;
        let password = document.getElementById("password").value;
        let params = `username=${username}&password=${password}`;
        //Send ajax request
        // 1. Create AJAX objects;
        let ajax = new XMLHttpRequest();

        // 2. Set request path, request mode, etc; Ajax.open (request mode, path)
        ajax.open('POST', '/login_post');
        
        ajax.setRequestHeader("enctype","application/x-www-form-urlencoded");
        // 3. Bind the processing function for monitoring the change of state, and the response data can be obtained in the processing function;
        ajax.onreadystatechange = ()=>{
            // Get the data from the response
            if(ajax.readyState===4&& ajax.status===200){
                console.log(ajax.readyState);
                console.log(ajax.responseText);
                // After the data is requested, the data can be updated to the page
                odiv.innerHTML = ajax.responseText;
            }
        };
        // 4. Send request.
        ajax.send(params)
    }
</script>

Server code:

else if(requestUrl=== "/login_post"){   //To handle requests for css files if the path contains. css
    request.on('data',(postData)=>{
        let uname = postData.toString().split("&")[0].split("=")[1];   // Gets the user name submitted by the user
        let pwd = postData.toString().split("&")[1].split("=")[1];    // Get the password submitted by the user

        if(uname===username && pwd===password){
            response.end("The account and password are correct, and the login is successful");
        }else{
            response.end("Account or password error, login failed");
        }
    });

}

ajax code extraction

        We know that we should modularize the project as much as possible for later project maintenance, so if this ajax code cannot be reused, the amount of code will be relatively large, which is not conducive to later maintenance of the project. We extract ajax into a file, turn it into a function, and call it when we need to send a request.

function ajax(mehtod, url, param, success, time){

    var ajax;
    
    //Dealing with compatibility issues when getting ajax
    try {       // Non IE 
        ajax = new XMLHttpRequest();
    }
    catch (e) { // IE
        ajax = new ActiveXObject('Microsoft.XMLHTTP');
    }

    if(method === 'get'){
        param = encodeURI(param);  //Chinese encoding processing for query parameters of get request
        url = url + '?' + param;
        param = null;
    }
    
    ajax.open(method, url);

    if(method === 'post'){
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }

    ajax.onreadystatechange = function () { // onload
        if(ajax.readyState == 4 && ajax.status == 200){
            success(ajax.responseText);
        }
    }
    
    ajax.send(param);

    var timer = setTimeout(function () {
        ajax.abort();
    }, time);
}

Using ajax in jQuery:

  • async: by default, all requests are asynchronous.

  • contentType: content encoding type when sending information to the server. The default is "application/x-www-form-urlencoded".

  • Data: the data sent to the server. It can be an object or a Key=value format string. If it is an object, it will be automatically converted to the request string format.

  • type: default: "GET". Other HTTP request methods, such as PUT and DELETE, can also be used, but it depends on the browser support.

  • url: the address to send the request. The default is the current page address.

  • dataType: the type of data expected to be returned by the server. If it is not specified, jQuery will automatically make intelligent judgment according to the mime information of the HTTP package. For example, the XML MIME type is recognized as xml, which can be left blank. The available values are: "xml", "html", "script", "json", "json" and "text".

  • cache: the default is true (the default is false when the dataType is script and jsonp. Setting it to false will disable caching.

  • Context: this object is used to set the context of AJAX related callback functions. That is, let this point in the callback function (if not specified as the current option).

  • beforeSend: before calling the request, this function can be used to check whether the request parameters are legitimate or not, such as adding a custom HTTP header. The XMLHttpRequest object is the only parameter. If false is returned in the function, the request can be cancelled.

  • success: the callback function after the request is successful. Parameters: the data returned by the server and processed according to the dataType parameter; A string describing the status.

  • $.ajax({
        url: 'url',
        type: 'GET',
        data: {username:'zs', password:'12345'},
        success: function(data){
            // Business logic of successful request
        }
    });

    Send GET request using jQuery

$.get('/get_data', {name:'nodejs', age:11}, function(data){
     //Business logic of successful request (operation after success)
});

      Sending POST requests using jQuery

$.post('url', {username:$("#username").val(), password:$("#password").val()}, function(data){
    // Business logic of successful request
    console.log(data);
});

Topics: Javascript html5 Ajax