Ajax| Program
AJAX, an acronym for Asynchronous JavaScript and XML, is a popular technology in today's fast-growing web development community. While this new technology provides great power, it also burns an indisputable argument over the "Back" button issue. The author of this article will explain how to use Ajax in the real world and how to evaluate its value in a project.
After you've finished reading this article, you'll understand what Ajax is, in what circumstances, and how and how to use it.
First, Introduction
AJAX, an acronym for Asynchronous JavaScript and XML, is the latest technical word. Asynchrony means that you can send a request to a server via Hypertext Transfer Protocol (HTTP) and continue processing additional data while waiting for the response. This means, for example, that you can call a server-side script to retrieve data in XML from a database, send the data to a server in a database, or simply load an XML file to populate your Web site without refreshing the page. However, while this new technology provides great power, it also raises a lot of controversy over the "Back" button issue. This article will help you determine when using AJAX is the best choice in the real world.
First, I assume you have a basic understanding of the acronym JavaScript and XML parts. Although you can request any type of text file via Ajax, I 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 have finished reading this article, you will understand what Ajax is, in what circumstances, and how and how to use the technology. You will learn how to create objects, make requests, and customize responses while maintaining a visual experience for the user.
I have created a sample project for this article (you can download the source code). This example implements a simple request-it loads an XML file that contains the content of the page and analyzes the data to display it in an HTML page.
Ii. General properties and methods
Tables 1 and 2 provide an overview of the properties and methods-they are supported by browsers such as Windows Internet Explorer 5,mozilla,netscape 7,safari 1.2, and opera.
Table 1 Properties
Property Description onReadyStateChange The event handler is active 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 a DOM-compliant document object from the server's response. Status code of the response from the server. StatusText the status message returned as a string.
Table 2 method
Method describes abort () to cancel the current HTTP request. getAllResponseHeaders () retrieves all HTTP header values. getResponseHeader ("Headerlabel") retrieves the value of an HTTP header from the body of the response. Open ("Method", "URL" [, asyncflag[, "UserName" [, "Password"]]) Initializes a msxml2.xmlhttp request, specifying 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 an HTTP header.
third, where to start
First, you need to create the XML file-we will request it later and analyze it as the 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. The request occurs when the page is loaded by using the OnLoad method in the page body. Next, the file requires an ID div tag so that we can locate the content when we are ready to display it. When you have finished all of these, the main body of your page looks as follows:
<body >
<div id="copy"></div>
</body>
Iv. Creating the Request object
In order to create the request object, you must check whether the browser uses XMLHttpRequest or ActiveXObject. The main difference between the two objects is the use of their browsers. Windows IE version 5 and above use ActiveX objects, while Mozilla,netscape 7,opera and Safari 1.2 and above use XMLHttpRequest objects. Another difference is the way you create objects: Opera,mozilla,netscape and Safari allow you to simply invoke the object's constructor, but Windows IE needs to pass the object's name to the ActiveX constructor. Here's 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");}
v. Issue of requests
Now that you have created your request, 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 the connection to get or post a custom url-this is a content.xml and set a Boolean definition-whether you want to make an asynchronous call.
Now it's time to make the request. In this example, I use NULL because we are using get; In order to use post, you need to send a query string using the following method:
request.onreadystatechange = onResponse;
request.open("GET". url, true);
request.send(null);
vi. customizing loading and error handling messages
The event handler that you create for the onReadyStateChange method is the place to centralize loading and handling errors. It is time to consider the user and provide feedback on the status of the content they interact with. In this instance, I provide feedback for all the Mount status codes and provide some basic feedback on the most frequently occurring error-handling status codes. To display the current state of the request object, the ReadyState property includes some values that appear in the following table.
值 描述0 未初始化,对象没有用数据进行初始化。1 装载中,对象正在装载它的数据。2 装载结束,对象完成了它的数据的装载。3 可交互,用户能与对象交互了,尽管它还没有装载结束。4 完成,对象已经完全被初始化。
There is a long list of definitions of HTTP status codes in the consortium. I have selected two status codes:
• 200: The request succeeded.
• 404: The server did not find anything that matched the requested file.
Finally, I check any other status code-they will generate an error and provide a generic error message. Here is a code example-you can use it to handle these situations. Notice that I'm locating the div ID that we created earlier in the body of the HTML file and applying mount and/or error information 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').innerHTML = "Sending Request...";}
if(obj.readyState == 1)
{ document.getElementById('copy').innerHTML = "Loading Response...";}
if(obj.readyState == 2)
{ document.getElementById('copy').innerHTML = "Response Loaded...";}
if(obj.readyState == 3)
{ document.getElementById('copy').innerHTML = "Response Ready...";}
if(obj.readyState == 4){
if(obj.status == 200){ return true; }
else if(obj.status == 404)
{
// 添加一个定制消息或把用户重定向到另外一个页面
document.getElementById('copy').innerHTML = "File not found";
}
else
{document.getElementById('copy').innerHTML = "There was a problem retrieving the XML."; }
}
When the status code is 200, this means that the request was successful. The following starts with a response.
VII. Analysis and Response
When you are ready to analyze the response from the requesting object, the real work begins. Now you can start working with the data you requested. For testing purposes only, you can use the ResponseText and Responsexml properties to display the raw data from the response during development. To access the nodes in the XML response, first use the request object you created, navigate to the Responsexml attribute to retrieve (you may have guessed) the XML from the response. Navigate to documentelement-It 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 with the node name. The following line uses a nodename of the head to locate a childnode:
response.getElementsByTagName('header')[0].firstChild.data;
Using Firstchild.data allows you to access the text in that element:
response.getElementsByTagName('header')[0].firstChild.data;
Here's 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').innerHTML = header;
viii. Demand Analysis
Now that you know how to use Ajax basics, 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 when you haven't refreshed the page yet. To do this, you can focus on a small part of your project-it can benefit from using this type of interaction. For example, you can create a form-it queries a script for real-time validation whenever a user enters an input field or a letter. You can create a drag-and-drop page-When you release an item, it can send the data to a script and save the page's state to a database. There is no doubt that the reasons for using AJAX exist, and this use is beneficial to both developers and users, depending on the specific conditions and performance.
There are other ways to solve the "back" button, such as using Google gmail-, which can now provide an undo function for your actions without refreshing the page. There will be many more creative examples-they will bring greater benefits to users by providing them with the tools to create a unique, real-time experience.
Ix. Conclusion
While Ajax allows us to build new and improved ways to interact with a Web page, as a developer, we need to keep in mind that the product is not technology-focused on the user and how it interacts with the user. Without a user base, the project we build is useless. Based on this standard, we can evaluate what technologies should be used and when to use them to create applications that are useful to the appropriate users.