Building better Web applications with Ajax technology

Source: Internet
Author: User
Tags format empty header key object model relative variable versions
ajax|web| Program

   First, Introduction

Asynchronous Javascript+xml, or Ajax, is a Web development technology that creates interactive Web applications. This program uses JavaScript and XML to submit server requests from the client, and it only needs to exchange a small amount of data throughout the process without having to submit the entire Web page. As a result, such programs will be faster and more responsive, and will be one of the key basic technologies for a new generation of client-server systems. You can see a good AJAX practice technology show at the site http://www.google.com/webhp?complete=1&hl=en. In this page, if you enter any letter into the text box, then a Drop-down list box appears, and the content comes directly from the server without having to submit the entire page. The core of Ajax is the XMLHttpRequest object. The client can retrieve and directly submit XML data in the background. In order to convert the retrieved XML data into the HTML content that can be generated, it is necessary to rely on the client Document Object Model (DOM) to read the XML document node tree and make up the visible HTML elements of the user. In fact, Ajax is not a single technology like html,dhtml, which combines different technologies:

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

· XML is commonly used as a format for transferring data back to the server (although it can be used in any format, such as plain text, HTML, etc.).

• If XML is used as a transformation format, then DOM is typically used with client-side scripting languages such as JavaScript to dynamically display and describe interactive information.

· XHTML (or HTML), CSS for markup and information formatting.

   second, the XMLHttpRequest object

Historically, it was Microsoft that first implemented the XMLHttpRequest object in an ActiveX object form in its Internet Explorer 5 for Windows. The Mozilla Engineering engineer then implemented a compatible native version of Mozilla 1.0 (and Netscape 7), and later Apple did the same job on safari 1.2. In fact, similar functionality is mentioned in the standard Document Object Model (DOM) level 3 loading and Storage specification of the consortium. Now, it becomes a de facto standard and starts to be implemented in most browsers that are released later.

(i) Creating objects

XMLHttpRequest objects are created differently depending on the browser. For Safari and Mozilla, the way they are created is as follows:

var req = new XMLHttpRequest ();
For Internet Explorer 5.0+ (5.0 and later), the object name is passed to the ActiveX constructor:

var req = new ActiveXObject ("Microsoft.XMLHTTP");
The method of this object controls all operations, and its properties store various pieces of data returned from the server, such as Xmlhttpobject.responsetext containing XML or string values returned from the server.

(ii) method

The methods for XMLHttpRequest objects supported in Windows IE 5.0+, Safari 1.2, and Mozila are listed below:

Method Describe
Abort () Cancels the current request. If you call it on an object that does not process the request (ReadyState 0 or 4), "The mysterious Thing" happens.
getResponseHeader ("Headerlabel") Returns the string value of a single header label
getAllResponseHeaders () Returns the complete header (label and value) collection as a string
Open ("Method", "URL" [, asyncflag[, "UserName" [, "Password"]]) Assign a destination URL, method, and other optional properties for a hanging request
Send (content) Transfer request. (optionally) which can be included in a sent string or DOM object data
setRequestHeader ("label", "value") Assign a label/value pair to the header in the request to be sent

In the above method, the open and send methods are the most important. Let's begin by discussing the open method from the point of view of the application.

var req;
...........................
req = new ActiveXObject ("Microsoft.XMLHTTP");
...............
var url= "Ajaxserver.aspx?" Pubid= "+ID;
...............
Opens a GET request to the URL
Req.open ("Get", url,true);
Actually send an empty request
Req.send (NULL);
   Attention

In this sample application, the Ajaxclient.aspx page is the user interface, and Ajaxserver.aspx is responsible for providing the data for each user request. It is particularly noteworthy that the Ajaxserver.aspx page should not contain any HTML. You can test what happens if the page contains HTML.

The first parameter of the Open method (see the Open function in the table above) indicates that the current exercise is either a get operation or a post operation. In simple data retrieval, get is generally used. Post is generally used when packets that are transmitted outward are larger than 512 bytes and operations include server-side activities such as inserts, updates, and so on. Next, let's take a look at the "url" parameter. This argument can be a complete URL or a relative URL. In the example above, the relative URL is used. The "Asyncflag" parameter indicates whether the incoming script is processed immediately after the Send method is executed (which means that there is no need to wait for a response). The last two parameters are "username" and "password", if the data is provided in the URL.

Another important method is the Send method, which actually sends the request using a message body. For this example, it simply sends a NULL request.

[
Actually send an empty request
Req.send (NULL);
]
(iii) property

Property Describe
onReadyStateChange The event handler for the event that fires whenever the state changes. Where the ReadyState object state integer meaning is as follows: 0=uninitialized1=loading2=loaded3=interactive4=complete
ResponseText String version of data returned after server processing
Responsexml DOM-compliant data document objects returned after server processing
Status The number code returned by the server, such as 404 for "not Found" and 200 for "OK"
StatusText String information along with the status code

In this case, the onreadystatechange is used in the application:

This is the event handler mechanism; In this case, "Requestprocessor" is the event handler.
Req.onreadystatechange=requestprocessor;
For this application, "Requestprocessor" is the event handler for the client. Now, within the event handler, use the ReadyState property to get a variety of states. A value of 4 shows that some processing has been completed. Now, before processing the results, you should check the status or StatusText to determine whether the operation is successful or not. In this application, I was implemented in the following way:

function Requestprocessor ()
{
If readystate handles the "Ready" state
if (req.readystate = 4)
{
Returned status code 200 means everything's fine.
if (Req.status = 200)
{
If ResponseText is not empty
Req.responsetext is actually a ajaxserver.aspx "Response.Write" ("" + sbxml.tostring () + ""); method to write a string
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 for the request destination must be in the same domain as the client script. The reason for this is that the XMLHttpRequest object uses the encapsulation technique consistent with client script. In most browsers that support this functionality, pages that have scripts to access XMLHttpRequest objects need to be retrieved using http: protocol. This means that you cannot test the page on a local hard drive (file: protocol).

   Iii. Practical Issues

In Ajax, what happens if a network or remote server is interrupted? In fact, there are two major problems; By default, they are not resolved in the XMLHttpRequest object. The two main issues are:

1. Processing latency: If a network or remote server spends more time, how does this problem relate to your AJAX application?

2. Response Order: Potentially, the network (or server) will change constantly. This means that the response may not be returned in the same order as the request.

To address these two issues, programmers must write code to solve the problem. For the first question, a possible scenario looks like this:

function Callinprogress (XMLHTTP) {
Switch (xmlhttp.readystate) {
Case 1,2,3:
return true;
Break
Case 4 and 0
Default
return false;
Break
}
}
Now, before you call Send (), I can check to see if the object is in a busy state:

if (!callinprogress (XMLHTTP)) {
Xmlhttp.send (NULL);
} else {
Alert ("I ' m busy.") Wait a Moment ");
}
(i) browsers that support Ajax technology

• Microsoft Internet Explorer version 5.0 and above, and browsers based on it (MAC OS version not supported)

• Gecko based browsers, such as Mozilla,mozilla Firefox,seamonkey,epiphany,galeon and Netscape versions 7.1 and above

• Implement Khtml API version 3.2 and above versions of browsers, including Konqueror version 3.2 and above, and Apple Safari version 1.2 and above

· Opera browser version 8.0 and above, including Opera mobile browser version 8.0 and above version

(ii) Browsers that do not support Ajax technology

· Opera 7 and the following version

• Microsoft Internet Explorer 4.0 and the following version

• Text-based browsers, such as Lynx and links

• Browsers with no visual implementation

• Browsers prior to 1997

(iii) sample application-specific requirements for this article

Software Requirements:

1.asp.net 2.0;

2.MS SQL Server 2000 and requires the appropriate pubs database settings;

3. Change the DB connection string ("Conn_string" key) in the Web.config file.

<APPSETTINGS>
<add value= "Data source=cal-slcu2-196;database=pubs; User=sa; Pwd=sa "key=" conn_string "/>
</APPSETTINGS>
The variable or class name should be included in the <code> tag as described above.

   Iv. Summary

This paper summarizes the main technologies and concepts of building next-generation popular Web applications based on Ajax technology, and gives an analysis of the key fragments of a complete sample 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.