Ajax asynchronous communication

Posted by rohithmr on Tue, 15 Feb 2022 14:58:42 +0100

Ajax overview

1. Function introduction (understanding)

Ajax, namely "Asynchronous Javascript And XML", refers to a web development technology for creating interactive web applications. Ajax can make web pages update asynchronously by exchanging a small amount of data with the server in the background. This means that a part of a web page can be updated without reloading the whole web page. Traditional web pages (without Ajax) must reload the whole web page if they need to update the content.

2. Applicable scenario (understanding)

Check whether the user name has been registered

Linkage of provincial and municipal couplet drop-down box

Automatic content completion

3. Concepts of synchronous request and asynchronous request

For example, to send three requests:

​ 1). Request for student information;

​ 2). Request for course information;

​ 3). Request for teacher information;

​ A). Synchronization: when sending a request, you need to wait for the response to return before you can send the next request. If the request has no response, you cannot send the next request, and you will be in the process of waiting all the time. (stuck)

​ 1). Send a request to get student information:

​ 2). Student information return

​ 3). Send request and obtain course information;

​ 4). Course information return

​ 5). Send a request to obtain teacher information;

​ 6). Teacher information return.

​ B). Asynchronous: Send a request without waiting for the response to return. You can send the next request at any time, that is, you don't need to wait. The result of the request can be obtained through the callback function.

​ 1). Send a request to get student information:

​ 2). Send request and obtain course information;

​ 3). Send a request to obtain teacher information;

​ 4). Student information return

​ 5). Course information return

​ 6). Teacher information return

Ajax plug-in for Jquery

jquery is an excellent js framework, which naturally encapsulates the native ajax of js. The operation method of encapsulated ajax is simpler and more powerful. There are several jquery methods related to ajax operation, but three are often used in development:

Request modegrammar
GET request$.get(url, [data], [callback], [type])
POST request$.post(url, [data], [callback], [type])
AJAX Request $.ajax([settings])

1.get request method

summary

Load information via remote HTTP GET request. This is a simple GET request function. For complex Ajax parameter settings, please use $ ajax.

grammar

jQuery.get(url, [data], [callback], [type])

The parameters are described as follows:

Parameter nameexplain
urlRequested server-side url address
dataThe request parameter sent to the server. The format can be key=value
callbackCallback function. After the server responds successfully, AJAX automatically calls the function
typeThe expected type of returned data. The values can be XML, HTML, script, JSON, text_ Defaul et al
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>use jQuery Frame encapsulated ajax of get Request mode</title>
    <!--Import jQuery External js file-->
    <script src="js/jquery-3.4.1.js"></script>
    <script>
        /*
            Requirement: when the page button is clicked, the function is triggered,
                 In the function, Ajax is used to obtain the data in a file on the server and display it in the div of the current page
         */
        //Define the loading event of the page: let the page load out first and use the elements in the page
        $(function () {
            /*
                get request mode of ajax encapsulated by jQuery framework
                jQuery.get(url, [data], [callback], [type])
                $.get(url, [data], [callback], [type])
                url:The path to the request server must be
                data:Data format sent to the server: k = V & K = v
                callback:Callback function. If the server returns data to the client successfully, the callback function will be executed automatically
                type:Preset the data type returned by the server (text (default), json)
             */
            //Get the button whose id is but and add a mouse click event to the button
            $("#but").click(function () {
                //In the response function of the event, send the get request method of ajax
                $.get(
                    "data/demo01.txt",
                    "username=jack&password=1234",
                    function (data) {//Callback function, the data returned by the server will be automatically assigned to the variable data of the callback function
                        //alert(data);
                        //Get the object whose id is myDiv, and set the label body as the data returned by the server
                        $("#myDiv").html(data);
                    },
                    "text"
                );
            });
        });
    </script>
</head>
<body>
    <input id="but" type="button" value="Send asynchronously ajax request"/>
    <div id="myDiv"></div>
</body>
</html>

2.ajax request mode

summary

Load remote data via HTTP request. The underlying AJAX implementation of jQuery. For easy-to-use high-level implementation, see get and post methods. $ ajax() method can set the underlying parameters in more detail.

grammar

jQuery.ajax([settings])
Among them, settings is a js literal object in the format of {name:value,name:value...}. The common name attribute names are as follows:

Attribute nameexplain
urlRequested server-side url address
async(default: true) by default, all requests are asynchronous. If you need to send a synchronization request, set this option to false
dataThe data sent to the server can be in the form of key value pair k = V & K = v
type(default: "GET") request method ("POST" or "GET"), default is "GET"
dataTypeThe type of data returned by the expected server. The values can be XML, HTML, script, JSON, text_ Defaul et al
successCallback function after successful request
errorThis function is called when the request fails
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>use jQuery Encapsulated ajax Bottom mode request server</title>
    <!--introduce jQuery file-->
    <script src="js/jquery-3.4.1.js"></script>
    <script>
        /*
            Requirement: when the page button is clicked, the function is triggered,
                 In the function, Ajax is used to obtain the data in a file on the server and display it in the div of the current page
         */
        //Page load event
        $(function () {
           /*
                 The ajax underlying method encapsulated by jQuery is used to request the server
                 jQuery.ajax(url,[settings])
                 $.ajax(url,[settings])
                 ajax The parameters set in the mode are set in the mode of key value pair
                 Format:
                    $.ajax({
                        url:The path to the request server,
                        async:Set asynchronous submission mode (true): asynchronous mode (do not write default); false: synchronization mode),
                        data:Data sent to the server, format k = V & K = V,
                        type:Set the method of requesting the server, get (no default), post,
                        dataType:Preset the data type returned by the server (text,json),
                        success:The callback function that requests the server to succeed,
                        error:The callback function of the server failed,
                        ...
                    });
            */
           //Get the button whose id is but and bind a mouse click event to the button
            $("#but").click(function () {
               //The response to the request is sent in the ajax function
               $.ajax({
                   url:"data/demo02.txt",
                   data:"username=jack&password=1234",
                   type:"get",
                   dataType:"text",
                   success:function (data) {//The callback function that successfully requests the server will assign the data returned by the server to data
                       //Put the data returned by the server into the tag body of div
                       $("#myDiv").html(data);
                   },
                   error:function () {
                       $("#myDiv").html(" server request failed! ");
                   }
               });
            });
        });
    </script>
</head>
<body>
    <input id="but" type="button" value="Send asynchronously ajax request"/>
    <div id="myDiv"></div>
</body>
</html>

3.ajax preset server returns data in json format

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>send out jQuery of ajax request</title>
    <!--introduce jQuery-->
    <script src="js/jquery-3.4.1.js"></script>
    <script>
        //Page load event
        $(function () {
            //Bind the mouse click event to the button whose id is but
            $("#but").click(function () {
                //Send ajax request for jQuery
                $.ajax({
                   url:"data/demo02.json",
                   dataType:"json",
                   success:function (data) {
                       //alert(data);// The return json is essentially an object [object]
                       //Object name Property name, get property
                       alert(data.firstname);
                       alert(data.lastname);
                       alert(data.age);
                   },
                   error:function () {
                       alert("Request server failed!")
                   }
                });
            });
        });
    </script>
</head>
<body>
<input id="but" type="button" value="Send asynchronously ajax request"/>
</body>
</html>

demo02.json

{
  "firstname": "Zhang",
  "lastname": "Sanfeng",
  "age": 100
}

Topics: Javascript JQuery Ajax