Ajax technology development application practice

Source: Internet
Author: User

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 this event processor is activated when the request object changes. Readystate returns the value indicating the current status of the object. Responsetext is the version of the response string from the server. Responsexml is a dom-compatible document object from the server's response. Status is the status code of the response from the server. Statustext returns status messages in the form of a string.

Table 2 Method

Method description abort () cancels the current HTTP request. GetAllResponseHeaders () Retrieves all HTTP header values. GetResponseHeader ("headerlabel") retrieves an HTTP header value from the response body. Open ("method", "url" [, asyncflag [, "username" [, "password"]) initializes an msxml2.xmlhttp request and specifies a method from the request, URL and authentication information. Send (content) sends an HTTP request to the server and receives 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 is not initialized, and the object is not initialized with data. 1. The object is loading its data. 2. After loading, the object loads its data. 3. Interaction: the user can interact with the object, even though 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:

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.