How to use AJAX for application development

Source: Internet
Author: User
Tags object definition error handling header html page string version access
Ajax| Program

Visitor, Hello! Transfer to Netcom Station | Switch to Telecom station building block Home | More than 500 kinds of Web page effects finishing | Practical Query Function Manual | Block network bt Download Alliance | Classic Jokes | Radio Stations | High-definition classic picture material
Program development web design search engine special effects code operating system Protection virus hacker technology graphic image Computer hardware network technology Server database net article pristine

Your location: Home >> program development channel >> Ajax Technology >> text: Title: How to use AJAX for application development time: 2005-12-22 Source: Internet Pick Browse Number: 156 times this source code download

Reading the Feed AJAX, an asynchronous JavaScript and XML acronym, 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:

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 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; ("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.

The value description 0 was uninitialized and the object was not initialized with data. 1 load, the object is loading its data. 2 The load ends, the object completes the load of its data. 3 can interact, the user can interact with the object, although it has not finished loading. 4 Complete, the object has been completely initialized.
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 = =) {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";
{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];
Using allows you to access the text in that element:

Response.getelementsbytagname (' header ') [0];
Here's a complete example of how to create this code:

var response = Request.responseXML.documentElement;
var header = Response.getelementsbytagname (' header ') [0];
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.

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: 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.