In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "how to use AJAX for WEB application development", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use AJAX for WEB application development" this article.
I. brief introduction
AJAX, an acronym for asynchronous JavaScript and XML, is a recent technical term. Async means that you can make a request to a server via Hypertext transfer Protocol (HTTP) and continue to process other data while waiting for the response. This means, for example, that you can call a server script to retrieve data in XML from a database, send the data to a server script stored in a database, or simply load a XML file to populate your Web site without refreshing the page. However, while this new technology provides great power, it has also caused a lot of debate over the issue of the "Back" button. This article will help you determine when to use AJAX in the real world is the best choice.
First of all, I assume you have a basic understanding of the acronym JavaScript and XML. Although you can request any type of text file through AJAX, I will focus on XML here. I will explain how to use AJAX in the real world and how to evaluate its value in a project. After you finish reading this article, you will understand what AJAX is, under what circumstances, why and how to use this technology. You will learn how to create objects, make requests, and customize responses while maintaining an intuitive experience for users.
I have created a sample project suitable for this article (you can download the source code). This example implements a simple request-it loads a XML file containing the contents of the page and parses the data to display it in a HTML page.
II. General attributes and methods
Tables 1 and 2 provide an overview of properties and methods that are supported by browsers such as Windows Internet Explorer 5, Mozilla, Netscape, 7, Safari 1.2, and Opera.
Table 1 attributes
Attribute description
Onreadystatechange the event handler is activated when the request object changes.
ReadyState returns a value indicating the current state of the object.
ResponseText the version of the response string from the server.
ResponseXML the DOM-compatible document object of the response from the server.
Status the status code of the response from the server.
A status message returned by statusText as a string.
Table 2 method
Method description
Abort () cancels the current HTTP request.
GetAllResponseHeaders () retrieves all HTTP header values.
GetResponseHeader ("headerLabel") retrieves the value of a HTTP header from the response body.
Open ("method", "URL" [, asyncFlag [, "userName" [, "password"]]) initializes a MSXML2.XMLHTTP request and specifies the method, URL, and authentication information from the request.
Send (content) sends an HTTP request to the server and receives a response.
SetRequestHeader ("label", "value") specifies the name of a HTTP header.
Third, where to start
First, you need to create a XML file-we'll request it later and analyze it as page content. The file you are requesting must reside on the same server as the target project.
Next, create the HTML file that makes the request. This request occurs when the page is loaded by using the onload method in the page body. Next, the file needs a div tag with ID so that we can locate the content when we are ready to display it. When you have done all this, the main body of your page goes up as follows:
< body onload=makeRequest ('xml/content.xml'); ">
< div id= "copy" > < / div >
< / body >
Create a request object
In order to create a request object, you must check whether the browser uses XMLHttpRequest or ActiveXObject. The main difference between these two objects is the browser that uses them. Windows IE 5 and above uses ActiveX objects, while Mozilla,Netscape 7 Magi Opera and Safari 1.2 and above use XMLHttpRequest objects. Another difference is the way you create an object: Opera,Mozilla, Netscape, and Safari allow you to simply call the object's constructor, but Windows IE needs to pass the object's name to the ActiveX constructor. Here is an example of how to create code to decide which object to use and how to create it:
If (window.XMLHttpRequest)
{request = new XMLHttpRequest ();}
Else if (window.ActiveXObject)
{request = new ActiveXObject ("MSXML2.XMLHTTP");}
5. Make a request
Now that you have created your request object, you are ready to send a request to the server. Create a reference to the event handler to listen to the onreadystatechange event. The event handler method will then respond when the state changes. Once we have completed the request, we begin to create this method. Open a connection to GET or POST a custom URL- here is a content.xml, and set a Boolean definition-whether you want to make an asynchronous call.
Now it's time to make a request. In this example, I use null because we are using GET; in order to use POST, you need to issue a query string using the following method:
Request.onreadystatechange = onResponse
Request.open ("GET". Url, true)
Request.send (null)
Custom loading and error handling messages
The event handler you create for the onreadystatechange method is the place to focus on loading and handling errors. It is time to consider users and provide feedback on the status of the content they are interacting with. In this example, I provide feedback on all load status codes, as well as some basic feedback on error handling status codes that occur most frequently. To display the current state of the request object, the readyState property includes some of the values shown in the following table.
Value description
0 is not initialized and the object is not initialized with data.
1 loading, the object is loading its data.
2 loading ends, and the object finishes loading its data.
3 is interactive, and the user can interact with the object, even though it has not been loaded yet.
4 complete, the object has been fully initialized.
There is a long list of definitions of HTTP status codes in the W3C. I chose two status codes:
200: the request was successful.
404: the server did not find anything that matches the requested file.
Finally, I check any other condition codes-they will generate an error and provide a general error message. Here is a code example-you can use it to handle these situations. Notice that I am locating the div ID we created earlier in the body of the HTML file and applying load and / or error messages to it-through the innerHTML method-this method is used to set the HTML between the start and end tags of the div object:
If (obj.readyState = = 0)
{document.getElementById ('copy') [xss_clean] = "Sending Request...";}
If (obj.readyState = = 1)
{document.getElementById ('copy') [xss_clean] = "Loading Response...";}
If (obj.readyState = = 2)
{document.getElementById ('copy') [xss_clean] = "Response Loaded...";}
If (obj.readyState = = 3)
{document.getElementById ('copy') [xss_clean] = "Response Ready...";}
If (obj.readyState = = 4) {
If (obj.status = = 200) {return true;}
Else if (obj.status = 404)
{
/ / add a custom message or redirect the user to another page
Document.getElementById ('copy') [xss_clean] = "File not found"
}
Else
{document.getElementById ('copy') [xss_clean] = "There was a problem retrieving the XML.";}
}
When the status code is 200, this means that the request was successful. Now it's time to respond.
7. Analyze the response
When you are ready to analyze the response from the request object, the real work begins. Now you can start working with the data you requested. For testing purposes only, during development, you can use the responseText and responseXML properties to display the raw data from the response. To access the node in the XML response, first use the request object you created and navigate to the responseXML property to retrieve (you may have guessed) the XML from the response. Locates to documentElement- which retrieves a reference to the root node of the XML response.
Var response = request.responseXML.documentElement
Now that you have a reference to the root node of the response, you can use getElementsByTagName () to retrieve the childNodes by the node name. The following line locates a childNode with a header nodeName:
Response.getElementsByTagName ('header') [0] .firstChild.data
Using firstChild.data allows you to access the text in this element:
Response.getElementsByTagName ('header') [0] .firstChild.data
Here is a complete example of how to create this code:
Var response = request.responseXML.documentElement
Var header = response.getElementsByTagName ('header') [0] .firstChild.data
Document.getElementById ('copy') [xss_clean] = header
VIII. Demand analysis
Now that you know the basics of how to use AJAX, the next step is to decide whether to use it in a project. The most important thing to remember is that you can't use the "Back" button before you refresh the page. To do this, focus on a small part of your project-it can benefit from using this type of interaction. For example, you can create a form that queries a script each time the user enters an input field or a letter for real-time verification. You can create a drag-and-drop page-when you release an item, it can send the data to a script and save the state of the page to a database. There is no doubt that there is a reason to use AJAX; and this use will benefit both developers and users; it all depends on the specific conditions and implementation.
There are other ways to solve the problem with the "Back" button, such as using Google Gmail-, which now provides an undo function for your actions without refreshing the page. There will be many more creative examples in the future-they will bring greater benefits to users by providing developers with the means to create unique real-time experiences.
The above is all the contents of the article "how to use AJAX for WEB application development". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.