Using Ajax to access background data

Keywords: Javascript Ajax

1, What is Ajax?

         Asynchronous Javascript + XML (asynchronous JavaScript and XML) is not a new technology in itself, but a 'new' method to describe a collection of existing technologies.

2, How to access background data?

         1. Create XMLHttpRequest object

         (1) Definition: XMLHttpRequest is used to exchange data with the server in the background. You can update a part of a web page without reloading the whole web page.
        (2) Create
            variable=new XMLHttpRequest();

        

function login(){
        var username=document.getElementById("username").value;
        var password=document.getElementById("password").value;
        //Create a new httpRequest object  
        var httpRequest=new XMLHttpRequest();

          2. Send a request to the server

                 (1) Definition: use the open() and send() methods of the XMLHttpRequest object.
                 (2) Syntax:
                        xmlhttp.open("GET","ajax_info.txt",true);
                        xmlhttp.send();
                (3)open(mehod,url,async)
                         Role: specify the type of request, URL and whether to process the request asynchronously.
                        Parameters:
                             1.method: type of request. get or post
                            2.url: the location of the file on the server
                             3.async: true (asynchronous) or false (synchronous)
                (4) send(string)
                        Function: send the request to the server.
                         Parameter: string (for post requests only.)

GET or POST?
            1.GET is simpler and faster than POST.
            2. Use post request when
                (1) Cannot use cache file (update file or database on server)
                (2) Send a large amount of data to the server (post has no data limit)
                (3) When sending user input containing unknown characters, post is more stable and reliable than get.

 //Configure the data format of the post request
        httpRequest.setRequestHeader('Content-Type',"application/json");
        //Initiate request 
        var obj={
            username:username,
            password:password,
        }
        var jsonObj=JSON.stringify(obj);
        //Transfer parameters
        httpRequest.send(jsonObj);

        There is a function setRequestHeader in the above code:

                setRequestHeader(header,value)
                     Role: add HTTP headers to requests
                    Parameters:
                        Header: Specifies the name of the header
                        Value: Specifies the value of the header

          3. Server response

                 (1) Definition: use the responseText or responseXML attribute of the XMLHttpRequest object.
                (2)responseText
                            Function: get response data in string form
                            Parameter: None
                (3)responseXML
                            Function: get response data in XML form
                             Parameter: None

//Processing response
        httpRequest.onreadystatechange=function(){
            if(httpRequest.readyState===4&&httpRequest.status===200){
                //Get response data
                var res=httpRequest.responseText;
                //console.log(res)
                var resObj=JSON.parse(res);
                console.log(resObj);
                if(resObj.status===200){
                    console.log("Login succeeded");
                    var token=resObj.data.token;
                    //Save the token to the session in the browser
                    sessionStorage.setItem("token",token);
                }else{
                    alert(resObj.message);
                }
            }
        }

        The above has an onreadystatechange event:

        When the request is sent to the server, we need to perform some response based tasks. The onreadystatechange event is triggered whenever the readyState changes.
        The XMLHttpRequest object has three important properties:
            1.onreadystatechange
                Store the function (or function name) and call it whenever the readyState property changes.
            2.readyState
                The status of XMLHttpRequest is stored.
                0: request not initialized
                1: Server connection established
                2: Request received
                3: Request processing
                4: The request has completed and the response is ready
            3.status
                200: "ok"
                404: page not found

Case:

        1. First write the login page link and background link of your project in the following code.

        2. When entering the correct user name and password, click login, and you will see the successful login from the console; After successful login, you can access the background data by clicking query all users and query user permissions respectively.

        html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User login</title>
    //Third party js files
    <script src="https://cdn.bootcdn.net/ajax/libs/qs/6.10.1/qs.min.js"></script>
    //Create a new js file
    <script src="ajax.js"></script>
</head>
<body>
    user name <input type="text" id="username">
    password  <input type="text" id="password">
    <br>
    <button onclick="login()">Sign in</button>
    <br>
    <hr>
    <button onclick="findAllUser()">Query all users</button>
    <button onclick="findMenuByUserId(25)">Query user permissions</button>
    <hr>
    <div id="main"></div>
</body>
<script>
    function login(){
        var username=document.getElementById("username").value;
        var password=document.getElementById("password").value;
        //Create a new httpRequest object  
        var httpRequest=new XMLHttpRequest();
        //Open connection to login page
        httpRequest.open("post",'http://...');
        //Configure the data format of the post request
        httpRequest.setRequestHeader('Content-Type',"application/json");
        //Initiate request 
        var obj={
            username:username,
            password:password,
        }
        var jsonObj=JSON.stringify(obj);
        //Transfer parameters
        httpRequest.send(jsonObj);
        //Processing response
        httpRequest.onreadystatechange=function(){
            if(httpRequest.readyState===4&&httpRequest.status===200){
                //Get response data
                var res=httpRequest.responseText;
                //console.log(res)
                var resObj=JSON.parse(res);
                console.log(resObj);
                if(resObj.status===200){
                    console.log("Login succeeded");
                    var token=resObj.data.token;
                    //Save the token to the session in the browser
                    sessionStorage.setItem("token",token);
                }else{
                    alert(resObj.message);
                }
            }
        }
    }
    function findAllUser(){
        //Create a request object
        var httpRequest=new XMLHttpRequest();
        //Open background connection
        httpRequest.open('get','http://...');
        //Get the token first
        var token=sessionStorage.getItem("token")
        if(token){
            //Configure token
            httpRequest.setRequestHeader('Authorization',sessionStorage.getItem('token'));
            //Initiate request
            httpRequest.send();
            //Processing response
            httpRequest.onreadystatechange=function(){
                if(httpRequest.readyState===4&&httpRequest.status===200){
                console.log(res);
                var res=httpRequest.responseText;
                document.getElementById("main").innerHTML=res;
            }
            }
        }else{
            alert("Please log in again");
        }
    }
    //Using encapsulated ajax
    function findMenuByUserId(id){
        myAjax.get('/baseUser/findMenuByUserId',{id:id},function(res){
            console.log("query was successful");
            console.log(res);
            
        },function(err){
            console.log("request was aborted");
            console.log(err);
        })
    }
</script>
</html>

        js code to be referenced:

var qs=Qs;
//Write a link to your project
var baseURL="http://...";
var myAjax={
    get:function(url,params,success,error){
        var httpRequest=new XMLHttpRequest();
        httpRequest.open('get',baseURL+url+'?'+qs.stringify(params));
        //Configure token
        httpRequest.setRequestHeader("Authorization",sessionStorage.getItem("token"));
        //Send request
        httpRequest.send();
        httpRequest.onreadystatechange=function(){
            if(httpRequest.readyState===4&&httpRequest.status===200){
                success(JSON.parse(httpRequest.responseText));
            }
            if(httpRequest.readyState===4&&httpRequest.status===500){
                error(JSON.parse(httpRequest.responseText));
            }
        }
    }
}

      

Posted by mac.php on Sat, 11 Sep 2021 15:31:26 -0700