Five steps for Ajax requests

What is Ajax

Ajax: asynchronous JavaScript and XML. AJAX is a technology used to create fast and dynamic web pages. 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 the web page can be updated without reloading the whole web page, while the traditional web page that does not use ajax must reload the whole web page if the content needs to be updated.

How Ajax works

The working principle of AJAX is quite about adding an intermediate layer (Ajax engine) between the user and the server to make the user operation asynchronous with the server response. Not all user requests are submitted to the server. For example, some data verification and data processing are left to the Ajax engine. Only when it is determined that new data needs to be read from the server, the Ajax engine submits the request to the server on behalf of the Ajax engine.

Traditional Web application model


Ajax Web application model

Basic steps to implement AJAX

To fully implement an AJAX asynchronous call and local refresh, the following steps are usually required:

1. To create an XML HttpRequest object is to create an asynchronous call object.
2. Create a new HTTP request and specify the method, URL and authentication information of the HTTP request
3. Set the function that responds to the status change of HTTP request.
4. Send HTTP request.
5. Gets the data returned by the asynchronous call.
6. Local refresh using JavaScript and DOM

1. Create XMLHttpRequest object

Different browsers use different asynchronous call objects. In IE browser, the asynchronous call uses the XMLHttpRequest object in the XMLHTTP component, while in Netscape and Firefox browsers, the XMLHttpRequest component is directly used. Therefore, the methods of creating XMLHttpRequest objects in different browsers are different.
How to create XMLHttpRequest object in IE browser

var XMLHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");

How to create XMLHttpRequest object in Netscape and Firefox browsers

var XMLHttpRequest = new XMLHttpRequest();

Since it is impossible to determine what browser the user is using, it is best to write both methods when creating the XMLHttpRequest object, as shown in the following code.

var xmlHttpRequest ;  // Create a variable to hold the XMLHttpRequest object
function createXMLHttpRequest() { 
    if(window.ActiveXObject()){  // Determine whether it is IE browser
        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP")
    }
    else if(window.XMLHttpRequest){  // Determine whether it is Netscape or other browsers that support XMLHttpRequest components
        xmlHttpRequest = new XMLHttpRequest()
    }
 }
 createXMLHttpRequest()  // Call the method that creates the object

If the browser supports neither ActiveX controls nor XMLHttpRequest components, the XMLHttpRequest variable will not be assigned

2. Create HTTP request

After creating the XMLHttpRequest object, you must create an HTTP request for the object to explain where the XMLHttpRequest object gets data.

XMLHttpRequest.open(method,URL,async,username,password)

Analysis of parameters:

1. The method parameter is the HTTP method used for the request. Values include GET, POST, HEAD, PUT, DELETE (case insensitive)

2. The URL parameter is the body of the request. Most browsers implement a same origin security policy and require that the URL have the same hostname and port as the text containing the script

3. The async parameter indicates that the request should be executed asynchronously. If this parameter is false, it means that the request is synchronous, and subsequent calls to send() will be blocked until the response is fully accepted; If this parameter is true or omitted, the request is asynchronous and usually requires an onreadystatechange event handle.

4. The username and password parameters are optional and provide authentication for the authorization required by the url. If specified, they override any qualifications specified by the url itself.

3. Set the function to respond to the status change of HTTP request

After creating the HTTP request, you can send the HTTP request to the Web server. The purpose of sending the HTTP request is to accept the data returned from the server. There are five states from creating XMLHttpRequest object to sending and receiving data

1. Uninitialized state. When the XMLHttpRequest object is created, the object is in an uninitialized state. At this time, the readyState property value of the XMLHttpRequest object is 0.

2. Initialization status. After creating the XMLHttpRequest object, when the HTTP request is created using the open() method, the object is in an initialized state. At this time, the readyState property value of the XMLHttpRequest object is 1.
3. Send data status. After initializing the XMLHttpRequest object, when sending data using the send() method, the object is in the send data state. At this time, the readyState property value of the XMLHttpRequest object is 2.
4. Receive data status. After receiving and processing the data, the Web server transmits the returned results to the client. At this time, the XMLHttpRequest object is in the state of receiving data, and the readyState property value of the XMLHttpRequest object is 3.
5. Completion status. After receiving data, the XMLHttpRequest object enters the completion state. At this time, the readyState property value of the XMLHttpRequest object is 4. At this time, the received data is stored in the memory of the client computer. You can use the responseText property or responseXml property to obtain the data.

The XMLHttpRequest object can only obtain the data returned from the server after the above five steps. Therefore, to obtain the returned data from the server, you must first judge the state of the XMLHttpRequest object.
The XMLHttpRequest object can respond to the readystatechange event, which is triggered when the state of the XMLHttpRequest object changes, that is, when the readyState property changes. Therefore, you can call a function through the readystatechange event to judge the readyState property value of the XMLHttpRequest object in the function, If readyState === 4, use the responseText property or responseXml property to get the data.

XMLHttpRequest.onreadystatechange = getData;  // Sets the function called when the state of the XMLHttpRequest object changes
function getData(){
    // Judge whether the readyState property value of XMLHttpRequest object is 4. If it is 4, it indicates that the asynchronous call is completed
    if(xmlHttpRequest.readyState === 4){
        // Statement to get data
    }
 }

4. Sets the statement that gets the data returned by the server

If the readyState property value of the XMLHttpRequest object is equal to 4, the asynchronous call process is completed. At this time, the data can be obtained. The completion of the asynchronous call process does not mean that the asynchronous call is successful. If you want to judge whether the asynchronous call is successful, you should also judge the status attribute value of XMLHttpRequest object. Only status === 200 indicates that the asynchronous call is successful.

If the HTML file is not running on the Web server, but running locally, XMLHttpRequest The return value of status is 0,

XMLHttpRequest.onreadystatechange = getData;  // Sets the function called when the state of the XMLHttpRequest object changes
function getData(){
    // Judge whether the readyState property value of XMLHttpRequest object is 4. If it is 4, it indicates that the asynchronous call is completed
    if(xmlHttpRequest.readyState === 4){
        if(xmlHttpRequest.status === 200 || xmlHttpRequest.status === 0 ){
            // Statement to get data
            document.write(xmlHttpRequest.responseText);//Output the returned result as a string
        }
    }
 }

5. Send HTTP request

After the above four steps, you can send the HTTP request to the Web server, using the send() method of XMLHttpRequest.

XMLHttpRequest.send(data)  
// Where data is an optional parameter. If the requested data does not require parameters, null can be used instead.

Example code:

<html>
<head>
<title>AJAX example</title>
<script language="javascript" type="text/javascript">    
    var xmlHttpRequest;  //Define a variable to hold the XMLHttpRequest object
    //Define a function to create an XMLHttpRequest object
    function createXMLHttpRequest(){
        if(window.ActiveXObject){//How to create IE browser
            xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }else if(window.XMLHttpRequest){//How to create in Netscape browser
            xmlHttpRequest = new XMLHttpRequest();
        }
    }
    //Functions that respond to HTTP request status changes
    function httpStateChange(){
        if(xmlHttpRequest.readyState == 4){//Judge whether the asynchronous call is successful. If successful, start to update the data locally
            if(xmlHttpRequest.status == 200||xmlHttpRequest.status == 0) {
                var node = document.getElementById("myDIv");//Find node
                node.firstChild.nodeValue = xmlHttpRequest .responseText;//Update data
            } else {//If the asynchronous call is not successful, a warning box will pop up and an error message will be displayed
                alert("error:HTTP The status code is:"+xmlHttpRequest.status + ",HTTP The status information is:" + xmlHttpRequest.statusText);
            }
        }
    }
    //Asynchronously invoking server segment data
    function getData(name,value){ 
        createXMLHttpRequest();//Create XMLHttpRequest object
        if(xmlHttpRequest!=null){     
            xmlHttpRequest.open("get","ajax.text",true);//HTTP request creation
            xmlHttpRequest.onreadystatechange = httpStateChange;//HTTP request status change function 
            xmlHttpRequest.send(null);//Send request
        }
    }
</script>
</head>
<body>
    <div id="myDiv">Original data</div>
    <input type = "button" value = "Update data" onclick = "getData()">
</body>
</html>

Keywords: Ajax

Added by phpchamps on Thu, 10 Feb 2022 09:22:59 +0200