Five steps for Ajax requests

catalogue

Five steps for Ajax requests

1, Definition

1. What is Ajax

2. The difference between synchronous and asynchronous

3. How ajax works

2, Basic steps to implement AJAX

1. Create pxmlh object

2. Create HTTP request

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

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

5. Send HTTP request

6. Local update

3, Complete AJAX instance

Five steps for Ajax requests

1, Definition

1. What is Ajax

Ajax: asynchronous JavaScript and XML. AJAX is a technology for creating 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 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. The difference between synchronous and asynchronous

Synchronous submission: when the user sends a request, the current page cannot be used. The server responds to the page to the client, and the user can use the page only after the response is completed.

Asynchronous submission: when the user sends a request, the current page can still be used. When the data of the asynchronous request is responded to the page, the page displays the data.

3. How ajax works

The client sends the request to xhr, xhr submits the request to the service, the server processes the business, the server responds to the data to the xhr object, the xhr object receives the data, and javascript writes the data to the page, as shown in the following figure:

2, 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 XMLHttpRequest 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. Sets 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. Use JavaScript and DOM to realize local refresh

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 way of creating XMLHttpRequest object in different browsers is different

The method of creating XMLHttpRequest object in IE browser is as follows:

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

The way to create XMLHttpRequest object in Netscape browser is as follows:

var xmlHttpRequest = new XMLHttpRequest();

Since it is impossible to determine what browser the user is using, it is best to add both methods when creating XMLHttpRequest objects As shown in the following code:

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

"if(window.ActiveXObject)" is used to judge whether to use IE browser ActiveXOject is not a standard attribute of Windows object, but a special attribute in IE browser, which can be used to judge whether the browser supports ActiveX controls Generally, only IE browser or browser with IE browser as the core can support Active control

"else if(window.XMLHttpRequest)" is a judgment made to prevent some browsers from supporting neither ActiveX controls nor XMLHttpRequest components XMLHttpRequest is not the standard attribute of window object, but it can be used to judge whether the browser supports XMLHttpRequest component

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

2. Create HTTP request

After the XMLHttpRequest object is created, an HTTP request must be created for the XMLHttpRequest object to indicate where the XMLHttpRequest object wants to get data. Usually it can be data in the website or data in other files in the local.

To create an HTTP request, you can use the open() method of the XMLHttpRequest object. Its syntax code is as follows:

XMLHttpRequest.open(method,URL,flag,name,password);

The parameters in the code are explained as follows:

  • Method: this parameter is used to specify the HTTP request method. There are five methods: get, post, head, put and delete. The commonly used methods are get and post.

  • URL: the URL used for the request can be either absolute or relative.

  • flag: this parameter is optional and its value is Boolean. This parameter specifies whether to use asynchronous mode. True indicates asynchrony, false indicates synchronization, and the default is true.

  • Name: this parameter is optional and used to enter the user name. This parameter must be used if the server requires authentication.

  • Password: this parameter is optional and used to enter the password. This parameter must be used if the server requires authentication.

You can usually use the following code to access the contents of a website file.

xmlHttpRequest.open("get","http://www.aspxfans.com/BookSupport/JavaScript/ajax.htm",true);

Or use the following code to access the contents of a local file:

xmlHttpRequest.open("get","ajax.htm",true);

Note: if the HTML file is placed on the Web server, the JavaScript security mechanism in the Netscape browser does not allow communication with hosts other than the local machine. That is, using the open() method can only open files on the same server as HTML files. There is no such restriction in IE browser (although you can open files on other servers, there will also be warning prompts).

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

After creating the HTTP request, you should be able to send the HTTP request to the Web server. However, the purpose of sending an HTTP request is to receive the data returned from the server. From the creation of XMLHttpRequest object to sending data, receiving data and XMLHttpRequest object, the following five states will be experienced.

  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.

Only after the XMLHttpRequest object completes the above five steps can it obtain the data returned from the server. Therefore, if you want to obtain the data returned from the server, you must first judge the state of the XMLHttpRequest object.

The XMLHttpRequest object can respond to the readystatechange event, which fires when the state of the XMLHttpRequest object changes (that is, when the readyState property value changes). Therefore, you can call a function through this event and judge the readyState property value of XMLHttpRequest object in this function. If the readyState property value is 4, use the responseText property or responseXml property to get the data. The specific code is as follows:

//Set the function to be called when the state of the XMLHttpRequest object changes. Be careful not to add parentheses after the function name
xmlHttpRequest.onreadystatechange = getData;

//Define function
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) {
        //Sets the statement that gets the 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, it indicates that the asynchronous call process is completed. You can obtain data through the responseText property or responseXml property of the XMLHttpRequest object.

However, 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 also need to judge the status attribute value of the XMLHttpRequest object. Only when the attribute value is 200, it means that the asynchronous call is successful. Therefore, to obtain the statement of data returned by the server, you must first judge whether the status attribute value of the XMLHttpRequest object is equal to 200, As shown in the following code:

 if(xmlHttpRequst.status == 200) {
    document.write(xmlHttpRequest.responseText);//Output the returned result as a string
    //document.write(xmlHttpRequest.responseXML);// Or output the returned results in XML
?}

Note: if the HTML file is not running on the Web server, but running locally, XMLHttpRequest The return value of status is 0. Therefore, if the file is running locally, you should add XMLHttpRequest Status = = 0.

The above code is usually placed in the function body in response to the status change of HTTP request, as shown in the following code:

//Set the function to be called when the state of the XMLHttpRequest object changes. Be careful not to add parentheses after the function name
xmlHttpRequest.onreadystatechange = getData;

//Define function
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){//Sets the statement that gets the data
            document.write(xmlHttpRequest.responseText);//Output the returned result as a string
????????????//docunment.write(xmlHttpRequest.responseXML);// Or output the returned results in XML
        }
    }
}

5. Send HTTP request

After setting the above steps, you can send the HTTP request to the Web server. send() method of XMLHttpRequest object can be used to send HTTP request, and its syntax code is as follows:

XMLHttpRequest.send(data);

Where data is an optional parameter. If the requested data does not require parameters, null can be used instead. The format of the data parameter is similar to that of the parameter passed in the URL. The following code is an example of the data parameter in the send() method:

name=myName&value=myValue

Only after using the send() method will the readyState property value of the XMLHttpRequest object begin to change, and the readystatechange event will be fired and the function will be called.

6. Local update

After obtaining the server-side data through the asynchronous call of Ajax, you can use JavaScript or DOM to locally update the data in the web page.

3, Complete AJAX instance

<html>
<head>
<title>AJAX example</title>
<script language="javascript" type="text/javascript">   
    function ajaxHttpRequestFunc(){
		let xmlHttpRequest;  // Create an XMLHttpRequest object, which is a variable used to hold the asynchronous call object
		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();
        }
		xmlHttpRequest.onreadystatechange=function(){ // Set events that respond to http request status changes
            console.log('Request process', xmlHttpRequest.readyState);
			if(xmlHttpRequest.readyState == 4){ // Judge whether the asynchronous call is successful. If successful, start to update the data locally
				console.log('The status code is', xmlHttpRequest.status);
				if(xmlHttpRequest.status == 200) {
					console.log('The data returned by asynchronous call is:', xmlHttpRequest .responseText);
					document.getElementById("myDiv").innerHTML = xmlHttpRequest .responseText; // Local refresh data to page
				} else { // If the asynchronous call is not successful, a warning box will pop up and the error status code will be displayed
					alert("error:HTTP The status code is:"+xmlHttpRequest.status);
				}
			}
		}
		xmlHttpRequest.open("GET","https://www.runoob.com/try/ajax/ajax_info.txt",true); / / create an http request and specify the method (get) and url of the request( https://www.runoob.com/try/ajax/ajax_info.txt )And verification information
		xmlHttpRequest.send(null); // Send request
    }
</script>
</head>
<body>
    <div id="myDiv">Original data</div>
    <input type = "button" value = "Update data" onclick = "ajaxHttpRequestFunc()">
</body>
</html>

Running this code directly may cause cross domain phenomenon. The error message of the console is as follows:

This is because the setting request in the code is the file of the service side of the rookie post station, so cross domain occurs, resulting in failure to obtain the data returned by the service side normally.

Solution: copy the code, paste it in the editor of rookie post station and run it.

Click the pre run page to display:

After clicking run, the page displays:

Well, that's all for ajax. Give yourself a big compliment!

reference:

[1]https://qqe2.com/java/post/28.html

[2]https://www.cnblogs.com/kennyliu/p/3876729.html

Keywords: node.js Front-end npm html

Added by gprobst on Thu, 03 Mar 2022 06:29:46 +0200