In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail the sample analysis of Ajax requests. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Definition 1. What is Ajax
Ajax: asynchronous JavaScript and XML. Ajax is a technology for creating fast dynamic web pages. By exchanging a small amount of data with the server in the background, Ajax can update web pages asynchronously. This means that some part of the page can be updated without reloading the entire page. However, traditional web pages (without using Ajax) must reload the entire web page if they need to update their content.
2. The difference between synchronous and asynchronous
Synchronous submission: when the user sends a request, the current page is not available, the server responds to the page to the client, and the response is completed before the user can use the page.
Asynchronous submission: the current page can continue to be used when the user sends the request, and when the asynchronous request data is responded to the page, the page displays the data.
3. The working principle of ajax
The client sends the request, the request is sent to xhr,xhr to submit the request to the service, the server performs business processing, the server responds to the data to the xhr object, the xhr object receives the data, and the javascript writes the data to the page, as shown in the following figure:
Second, the basic steps of implementing AJAX
To fully implement an AJAX asynchronous call and local refresh, you usually need the following steps:
Create a XMLHttpRequest object, that is, create an asynchronous invocation object.
Create a new HTTP request and specify the method, URL, and authentication information for the HTTP request.
Sets a function that responds to a change in the state of an HTTP request.
Send a HTTP request.
Gets the data returned by the asynchronous call.
Use JavaScript and DOM to achieve local refresh.
1. Create a XMLHttpRequest object
Different browsers use different asynchronous invocation objects. Asynchronous invocation uses XMLHttpRequest objects in XMLHTTP components in IE browsers, while XMLHttpRequest components are directly used in Netscape and Firefox browsers. As a result, XMLHttpRequest objects are created differently in different browsers.
You can create a XMLHttpRequest object in an IE browser by:
Var xmlHttpRequest = new ActiveXObject ("Microsoft.XMLHTTP")
You can create a XMLHttpRequest object in a Netscape browser by:
Var xmlHttpRequest = new XMLHttpRequest ()
Since it is impossible to determine which browser the user is using, it is best to add both of the above methods when creating XMLHttpRequest objects. As shown in the following code:
Var xmlHttpRequest; / / defines a variable to store the XMLHttpRequest object createXMLHttpRequst (); / / calls the method to create the object / / the method to create the XMLHttpRequest object function createXMLHttpRequest () {if (window.ActiveXObject) {/ / to determine whether it is an IE browser xmlHttpRequest = new ActiveXObject ("Microsoft.XMLHTTP") / / create a XMLHttpRequest object of IE} else if (window.XMLHttpRequest) {/ / determine whether it is a browser xmlHttpRequest = new XMLHttpRequest () that supports XMLHttpRequest components such as Netscape; / / create a XMLHttpRequest object on other browsers}}
"if (window.ActiveXObject)" is used to determine whether or not to use an IE browser. ActiveXOject is not a standard property of Windows object, but a special property in IE browser, which can be used to judge whether the browser supports ActiveX control. Usually only IE browsers or browsers with IE browsers as the core can support Active controls.
Else if (window.XMLHttpRequest) is a judgment made to prevent some browsers from supporting neither ActiveX nor XMLHttpRequest components. XMLHttpRequest is not a standard attribute of window object, but it can be used to judge whether browsers support XMLHttpRequest components.
If the browser supports neither ActiveX nor XMLHttpRequest components, then the xmlHttpRequest variable will not be assigned a value.
2. Create a HTTP request
After you have created the XMLHttpRequest object, you must create an HTTP request for the XMLHttpRequest object to indicate where the XMLHttpRequest object is going to get the data. It can usually be data from a Web site or from other files locally.
To create a HTTP request, you can use the open () method of the XMLHttpRequest object, whose 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 request method of HTTP. There are five methods: get, post, head, put and delete. The commonly used methods are get and post.
URL: this parameter is used to specify the URL address of the HTTP request, either absolute URL or relative URL.
Flag: this parameter is optional and the parameter value is Boolean. This parameter is used to specify whether to use asynchronous mode. True means async, false means synchronization, and the default is true.
Name: this parameter is optional and is used to enter a user name. This parameter must be used if the server requires authentication.
Password: this parameter is optional and is used to enter a password. This parameter must be used if the server requires authentication.
You can usually use the following code to access the contents of a Web site 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 you to communicate with hosts other than this machine. That is, using the open () method can only open files that are on the same server as the HTML file. There is no such restriction in IE browsers (although you can open files on other servers, there is also a warning prompt).
3. Set the function that responds to the status change of the HTTP request
After you have created 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 data returned from the server. From the creation of the XMLHttpRequest object, to sending data, receiving data, and XMLHttpRequest objects will experience a total of the following 5 states.
Uninitialized state. When the XMLHttpRequest object is created, it is in an uninitialized state, and the readyState property value of the XMLHttpRequest object is 0.
Initialize the state. When the HTTP request is created using the open () method after the XMLHttpRequest object is created, the object is in an initialized state. The value of the readyState property of the XMLHttpRequest object is 1.
Send data status. After initializing the XMLHttpRequest object, when sending data using the send () method, the object is in the send data state, and the readyState property value of the XMLHttpRequest object is 2.
Receive data status. After the data is received and processed by the Web server, the returned result is transmitted to the client. At this point, the XMLHttpRequest object is in the state of receiving data, and the readyState property value of the XMLHttpRequest object is 3.
Completion status. After the XMLHttpRequest object has finished receiving the data, it enters the completion state, where the readyState property value of the XMLHttpRequest object is 4. At this point, the received data is stored in the memory of the client computer, and you can use the responseText property or the responseXml property to get the data.
The data returned from the server can be obtained only after the XMLHttpRequest object has completed the above five steps. Therefore, if you want to get the data returned from the server, you must first determine 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 value of the readyState property changes). Therefore, you can call a function through this event and determine the value of the readyState property of the XMLHttpRequest object in that function. If the readyState property value is 4, use the responseText property or the 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. Note that do not add parentheses xmlHttpRequest.onreadystatechange = getData; / / define the function function getData () {/ / determine whether the readyState attribute value of the XMLHttpRequest object is 4. If 4 indicates that the asynchronous call completes the if (xmlHttpRequest.readyState = = 4) {/ / set the statement}} 4 to get the data returned by the server.
If the value of the readyState property of the XMLHttpRequest object is equal to 4, the asynchronous invocation process is complete, and the data can be obtained through the responseText property or the 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 determine whether the asynchronous call is successful, you should also judge the status property value of the XMLHttpRequest object. Only if the attribute value is 200, the asynchronous call is successful. Therefore, to get the statement that the server returns data, you must also determine whether the status attribute value of the XMLHttpRequest object is equal to 200, as shown in the following code:
If (xmlHttpRequst.status = = 200) {[xss_clean] (xmlHttpRequest.responseText); / / output the result as a string / / [xss_clean] (xmlHttpRequest.responseXML); / / or output the result as XML}
Note: if the HTML file is not running on the Web server, but locally, the return value of xmlHttpRequest.status is 0. Therefore, if the file is running locally, you should add the judgment of xmlHttpRequest.status = = 0.
The above code is usually placed inside the function that responds to the state change of the HTTP request, as shown in the following code:
/ / set the function to be called when the state of the XMLHttpRequest object changes. Do not add parentheses xmlHttpRequest.onreadystatechange = getData after the function name. / / define the function function getData () {/ / determine whether the readyState attribute value of the XMLHttpRequest object is 4. If 4 means that the asynchronous call completes if (xmlHttpRequest.readyState==4) {if (xmlHttpRequest.status = = 200 | | xmlHttpRequest.status = = 0) {/ / sets the statement [xss_clean] (xmlHttpRequest.responseText) to get the data; / / outputs the returned result as a string / / docunment.write (xmlHttpRequest.responseXML) / / or output the returned result in the form of XML} 5, send the HTTP request
After setting up the above steps, you can send the HTTP request to the Web server. To send a HTTP request, you can use the send () method of the XMLHttpRequest object, whose syntax code is as follows:
XMLHttpRequest.send (data)
Where data is an optional parameter, if the requested data does not require a parameter, you can use null instead. The format of the data parameter is similar to that passed in URL, and the following code is an example of the data parameter in the send () method:
Name=myName&value=myValue
It is only after using the send () method that the value of the readyState property of the XMLHttpRequest object starts to change, the readystatechange event is fired, and the function is called.
6. Local updates
After the server-side data is obtained through the asynchronous call of Ajax, you can use JavaScript or DOM to partially update the data in the web page.
3. Complete AJAX instance
AJAX instance function ajaxHttpRequestFunc () {let xmlHttpRequest; / / create XMLHttpRequest object, that is, a variable if (window.ActiveXObject) {/ / IE browser creation method xmlHttpRequest = new ActiveXObject ("Microsoft.XMLHTTP");} else if (window.XMLHttpRequest) {/ / Netscape browser creation method xmlHttpRequest = new XMLHttpRequest () } xmlHttpRequest.onreadystatechange=function () {/ / sets the event console.log ('request process', xmlHttpRequest.readyState) in response to a change in the status of the http request If (xmlHttpRequest.readyState = = 4) {/ / determine whether the asynchronous call is successful. If you successfully start locally updating the data console.log ('status code is', xmlHttpRequest.status) If (xmlHttpRequest.status = = 200) {console.log ('the data returned by the asynchronous call is:', xmlHttpRequest. ResponseText); document.getElementById ("myDiv") [xss_clean] = xmlHttpRequest. ResponseText / / partially refresh data to the page} else {/ / if the asynchronous call is not successful, a warning box pops up with the error status code alert ("error:HTTP status code:" + xmlHttpRequest.status) } xmlHttpRequest.open ("GET", "https://www.runoob.com/try/ajax/ajax_info.txt",true);" / / create a http request and specify the request method (get), url (https://www.runoob.com/try/ajax/ajax_info.txt) and verification information xmlHttpRequest.send (null); / / send the request} original data
Running this code directly may cause cross-domain phenomenon. The error message in the console is as follows:
This is because the request in the code is the file of the rookie post server, so the cross-domain causes the data returned by the server not to be obtained normally.
Solution: copy this code and paste and run it in the editor of the rookie station.
Click the pre-run page to display as:
Click to run and the page appears as follows:
This is the end of this article on "sample Analysis of Ajax requests". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.