Use Ajax technology to build better Web Applications

Source: Internet
Author: User
I. Introduction

Asynchronous JavaScript + XML (Ajax) is a method for creating interactive web applications.ProgramWeb development technology. This type of program uses JavaScript and XML to submit server requests from the client, and only a small amount of data needs to be exchanged throughout the process without submitting the entire web page. Therefore, such a program will be faster and more responsive, and will become one of the important basic technologies of the next-generation client-server system. Can you http://www.google.com/webhp at the site? Complete = 1 & HL = EN shows a good demonstration of Ajax practices. On this page, if you enter any letter in the text box, a drop-down list box will appear. The content is directly from the server without submitting the entire page. The core of AJAX is the XMLHTTPRequest object. The client can retrieve and directly submit XML data in the background. To convert the retrieved XML data into HTML content that can be generated, You need to rely on the client Document Object Model (DOM) to read the XML document node tree and form HTML elements visible to users. In fact, Ajax is not a single technology like HTML or DHTML. It combines different technologies:

· The XMLHTTPRequest object is used to exchange data asynchronously with the Web server.

· XML is widely used to transfer data back to the server (although it can be used in any format, such as plain text and HTML ).

· If XML is used as the conversion format, Dom is usually used with client scripting languages such as JavaScript to dynamically display and describe interaction information.

· XHTML (or HTML), CSS is used for tag and information formatting.

Ii. XMLHTTPRequest object

In history, Microsoft first implemented the XMLHTTPRequest object in the form of an ActiveX Object in Internet Explorer 5 for Windows. Later, Mozilla engineering engineers implemented a compatible native version of Mozilla 1.0 (and Netscape 7), while Apple later achieved the same work on its Safari 1.2. In fact, similar functions are also mentioned in W3C standard Document Object Model (DOM) Level 3 loading and storage specifications. Now, it becomes a de facto standard and will be implemented in most browsers released in the future.

(1) create an object

The method for creating XMLHttpRequest objects varies with the browser. For Safari and Mozilla, the creation method is as follows:

VaR Req = new XMLHttpRequest ();

For Internet Explorer 5.0 + (5.0 and later), you must pass the object name to the ActiveX constructor:

VaR Req = new activexobject ("Microsoft. XMLHTTP ");

The method of this object controls all operations, and its attributes store various data fragments returned from the server, for example, xmlhttpobject. responsetext contains XML or string values returned from the server.

(2) Method

The XMLHttpRequest objects supported in Windows IE 5.0 +, Safari 1.2, and ILA are listed as follows:

Method Description
Abort () Cancels the current request. If you call it on an object that does not process a request (readystate 0 or 4), the "mysterious thing" happens.
GetResponseHeader ("headerlabel ") Returns the string value of a single header tag.
GetAllResponseHeaders () Returns a complete set of headers (tags and values) in the form of a string.
Open ("method", "url" [, asyncflag [, "username" [, "password"]) Specify the target URL, method, and other optional attributes of a hanging request.
Send (content) Transmission request. (Optional) it can contain shipping strings or DOM object data.
SetRequestHeader ("label", "value ") Assign a tag/value pair to the header of the request to be sent.

In the preceding method, the open and send methods are the most important. Next, let's first discuss the open method from the perspective of the application.

VaR req;
...........................
Req = new activexobject ("Microsoft. XMLHTTP ");
...............
VaR url = "ajaxserver. aspx? Pubid = "+ ID;
...............
// Open a GET request to the URL
Req. Open ("get", URL, true );
// Actually send an empty request
Req. Send (null );

Note:

In this example, the ajaxclient. ASPX page is a user interface, and ajaxserver. aspx is responsible for providing data for each user request. Note that the ajaxserver. ASPX page should not contain any HTML. You can test what will happen if the page contains HTML.

The first parameter of the open method (see the open function in the preceding table) indicates that the current operation is a get or post operation. Get is generally used for simple data retrieval. Generally, post is used when the data packets transmitted outward are larger than 512 bytes and the operations include server-side activity (such as insertion and update. Next, let's take a look at the URL parameters. This parameter can be either a complete URL or a relative URL. In the above example, the relative URL is used. The "asyncflag" parameter indicates whether to process the script that comes immediately after the send method is executed (this means you do not have to wait for a response ). The last two parameters are "username" and "password", if the data is provided in "url.

Another important method is the send method, which actually uses a message body to send requests. In this example, it only sends an empty request.

[
// Actually send an empty request
Req. Send (null );
]

(3) attributes

Attribute Description
Onreadystatechange Event processor of events that are triggered whenever the status changes. The status integer of the readystate object has the following meanings: 0 = uninitialized1 = loading2 = loaded3 = interactive4 = complete
Responsetext String version of the data returned after processing by the server
Responsexml Dom-compatible data document objects returned after server processing
Status Number returned by the serverCodeFor example, 404 stands for "not found" and 200 stands for "OK"
Statustext String information accompanied by status code

Here, the application uses onreadystatechange:

// This is the event processor mechanism. In this example, "requestprocessor" is the event processor.
Req. onreadystatechange = requestprocessor;

For this application, "requestprocessor" is the event processor of the client. Now, in the event processor, use the readystate attribute to obtain various States. Value 4 indicates that some processing has been completed. Now, before processing the result, you should check the status or statustext to determine whether the operation is successful or not. In this application, I implement the following method:

Function requestprocessor ()
{
// If readystate processes the "ready" status
If (req. readystate = 4)
{
// The returned status code 200 means everything goes well
If (req. Status = 200)
{
// If responsetext is not empty
// Req. responsetext is actually a string written by ajaxserver. aspx "response. Write (" "+ sbxml. tostring () + "");"
If (req. responsetext! = "")
{
Populatelist (req. responsexml );
}
Else
{
Clearselect (publishedbooks );
}
}
}
Return true;
}

Note that the object req is declared as a page-level variable:

VaR Req = new activexobject ("Microsoft. XMLHTTP ");

Warning

The URL of the request must be in the same domain as the client script. The reason is that the XMLHTTPRequest object adopts the same encapsulation technology as the client script. In most browsers that support this function, pages that have scripts to access the XMLHTTPRequest object must be retrieved using http: protocol. This means that you cannot perform a page test on a local hard disk (File: Protocol.

Iii. Actual Problems

In Ajax, what happens if the network or remote server is interrupted? In fact, there are two main problems. By default, they are not solved in the XMLHTTPRequest object. The two main problems are:

1. Processing latency: if the network or remote server consumes a lot of time, how can this problem be linked to your Ajax application?

2. response sequence: The network (or server) may change constantly. This means that the response may not be returned in the same order as the request.

To solve the above two problems, the programmer must write code to solve the problem. A possible solution for the first problem is as follows:

Function callinprogress (XMLHTTP ){
Switch (XMLHTTP. readystate ){
Case 1, 2, 3:
Return true;
Break;
// Case 4 and 0
Default:
Return false;
Break;
}
}

Now, before calling send (), I can check whether the object is in a busy state:

If (! Callinprogress (XMLHTTP )){
XMLHTTP. Send (null );
} Else {
Alert ("I'm busy. Wait a moment ");
}

(1) browsers supporting Ajax technology

· Microsoft Internet Explorer version 5.0 and later, and its browser (not supported by Mac OS)

· Gecko-based browsers, such as Mozilla, Mozilla Firefox, SeaMonkey, epiphany, galeon, and Netscape versions 7.1 and later

· Browsers that implement khtml API version 3.2 and later, including Konqueror version 3.2 and later, and Apple Safari version 1.2 and later

· Opera browser version 8.0 and later, including opera mobile browser version 8.0 and later

(2) browsers that do not support Ajax technology

· Opera 7 and earlier versions

· Microsoft Internet Explorer 4.0 and earlier

· Text-based browsers, such as lynx and links

· Browsers without Visualization

· Web browsers before January 1, 1997

(3) Specific requirements of the sample application in this article

Software requirements:

1. ASP. NET 2.0;

2. ms SQL Server 2000, and the corresponding pubs database settings are required;

3. Change the DB connection string ("conn_string") in the web. config file ).

<Deleetask>
<Add value = "Data Source = cal-slcu2-196; database = pubs; user = sa; Pwd = sa" Key = "conn_string"/>
</Appsettings>

Variables or class names should be included in the <code> mark as above.

Iv. Summary

This article summarizes the main technologies and related concepts of building next-generation popular Web applications based on AJAX technology, and gives an analysis of key pieces of a complete example program.

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.