Practical application development using Ajax technology

Source: Internet
Author: User
Practical application development using Ajax technology

Ajax, An Asynchronous JavaScript and XML acronyms, is a very popular technology in today's rapidly developing web development field. While this new technology provides tremendous capabilities, it also ignited an unquestionable debate over the "back" button. This article explains how to use Ajax in the real world and how to evaluate its value in a project. After reading this article, you will understand what Ajax is, under what circumstances, why, and how to use this technology.
I. Introduction

Ajax, An Asynchronous JavaScript and XML acronyms, is a recent technical term. Asynchronous means that you can send a request to a server through Hypertext Transfer Protocol (HTTP) and continue processing other data while waiting for the response. This means that, for example, you can call a server script to retrieve data from a database in XML format and send the data to the server script stored in a database, or simply load an XML file to fill your web site without refreshing the page. However, while the new technology provides great capabilities, it also raises a lot of debate over the "back" button. This article will help you determine when Ajax is the best choice in the real world.

First, I suppose you have a basic understanding of the acronyms JavaScript and XML. Although you can request any types of text files 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 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, send requests, and customize responses while maintaining an intuitive user experience.

I have created a sample project suitable for this article (you can download the source code ). This example implements a simple request-it loads an XML file containing the page content and analyzes the data to display it in an HTML page.

II. General attributes and Methods

Tables 1 and 2 provide an overview of properties and methods-they 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 processor is activated when the request object changes.
Readystate Returns the value indicating the current status of the object.
Responsetext The version of the response string from the server.
Responsexml Dom-compatible document objects for responses from the server.
Status The status code of the response from the server.
Statustext Status message returned in the form of a string.

Table 2 Method

Method Description
Abort () Cancels the current HTTP request.
GetAllResponseHeaders () Retrieve all HTTP header values.
GetResponseHeader ("headerlabel ") Retrieve the value of an HTTP header from the response body.
Open ("method", "url" [, asyncflag [, "username" [, "password"]) Initialize an msxml2.xmlhttp request and specify the method, URL, and authentication information from the request.
Send (content) Send an HTTP request to the server and receive the response.
SetRequestHeader ("label", "value ") Specifies the name of an HTTP header.

III. Where to start

First, you need to create an XML file-we will request it 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 requested HTML file. This request occurs when the page is loaded by using the onload method in the page body. Next, the file needs an ID Div tag, so that we can locate it when we are ready to display the content. After you finish all this, the subject of your page looks as follows:

<Body onload = "makerequest ('xml/content. xml');">
<Div id = "copy"> </div>
</Body>

4. Create a request object

To create a request object, you must check whether the browser uses XMLHttpRequest or activexobject. The main difference between the two objects is that they are used in the browser. Windows ie 5 and later versions use ActiveX objects, while Mozilla, Netscape 7, opera, Safari 1.2 and later use XMLHttpRequest objects. Another difference is that you can create an object by using opera, Mozilla, Netscape, and safari. You can simply call the object constructor, however, Windows ie needs to pass the object name to the ActiveX constructor. The following is an example of how to create code to determine 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. Send a request

Now that you have created your request object, you have prepared for sending a request to the server. Create a reference to the event processor to listen to the onreadystatechange event. The event processor method then responds when the status changes. Once the request is completed, we start to create this method. Open the connection to get or post a custom URL-here it is a content. XML, and set a Boolean definition-whether you want to make asynchronous calls.

Now it's time to send the request. In this example, I use null because we use get. To use post, you need to use the following method to issue a query string:

Request. onreadystatechange = onresponse;
Request. Open ("get". url, true );
Request. Send (null );

6. Custom loading and error handling messages

The event processor you created for the onreadystatechange method is the place where errors are loaded and handled in a centralized manner. Now it is time to consider users and provide feedback on the status of the content they interact. In this instance, I provide feedback on all the Load Status Code and some basic feedback on the most frequently occurring error handling status code. To display the current status of the request object, the readystate attribute includes values shown in the following table.

Value Description
0 The object is not initialized. No data is used for initialization.
1 Loading, the object is loading its data.
2 After the loading is complete, the object loads its data.
3 Interactive, the user can interact with the object, although it has not been loaded.
4 The object has been fully initialized.

W3C has a long string of HTTP status code definitions. I have selected two status codes:

· 200: the request is successful.

· 404: the server does not find anything that matches the requested file.

Finally, I check any other status code-they will generate an error and provide a general error message. The following is an example of Code-you can use it to handle these situations. Note, I am positioning the DIV ID created in the subject of the HTML file before and apply the load and/or error information to it-using the innerhtml method-this method is used to set the start and end of the DIV object HTML between ending tags:

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)
{
// Add a custom message or redirect the user to another page
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 the request is successful. The response is started below.

VII. Analysis and 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, you can use the responsetext and responsexml attributes during development to display the raw data from the response. To access the nodes in the XML response, first use the request object you created and locate the responsexml attribute to retrieve the XML from the response (which you may have guessed. Go to documentelement-It retrieves a reference for the root node of the XML response.

VaR response = request.responsexml.doc umentelement;

Now that you have a reference to the response root node, you can use getelementsbytagname () to retrieve childnodes by node name. The following line uses a nodename header to locate a childnode:

Response. getelementsbytagname ('header') [0]. firstchild. Data;

Using firstchild. Data allows you to access text in this element:

Response. getelementsbytagname ('header') [0]. firstchild. Data;

The following is a complete example of how to create the Code:

VaR response = request.responsexml.doc umentelement;
VaR header = response. getelementsbytagname ('header') [0]. firstchild. Data;
Document. getelementbyid ('copy'). innerhtml = header;

VIII. Requirement Analysis

Now that you know how to use Ajax, the next step is to determine whether to use Ajax in a project. The most important thing to remember is that you cannot use the "back" button before refreshing the page. 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 that queries a script each time you enter an input field or letter for real-time verification. You can create a drag-and-drop page-when releasing an item, it can send data to a script and save the status of the page to a database. There is no doubt that the reason for using Ajax exists, and such use will bring benefits to both developers and users. This is all dependent on specific conditions and execution conditions.

There are other ways to solve the "back" button problem, such as using Google Gmail-it can now provide an Undo function for your operations without refreshing the page. There will be many more creative examples in the future-they will bring more benefits to users by providing developers with unique real-time experience.

IX. Conclusion

Although Ajax allows us to build new and improved ways to interact with a web page, as a developer, we need to remember that the product does not consider technology; it cares about users and how they interact with users. 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 corresponding users.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.