Ajax Core Object--the use of XMLHttpRequest object (i)

Source: Internet
Author: User
Tags add object error handling html page connect version variable domain name
Ajax|request|xml|xmlhttprequest| Objects | Details Most WEB applications use the request/response model to obtain complete HTML pages from the server. Often click on a button, wait for the server to respond, and then click another button, and then wait, such a repetitive process. With Ajax and XMLHttpRequest objects, you can use a request/response model that eliminates the need for the user to wait for a response from the server. In this article, Brett McLaughlin describes how to create a XMLHttpRequest instance that adapts to different browsers, builds and sends requests, and responds to the server.

In this article, you will begin to touch the most basic and basic Ajax-related objects and programming methods: XMLHttpRequest objects. This object is actually just a public thread spanning all Ajax applications, and you may have expected that only a thorough understanding of the object would give full play to the potential of programming. In fact, sometimes you'll find that you can't use XMLHttpRequest to use XMLHttpRequest correctly. What the hell is going on here?

   Web 2.0 Glimpse

Before delving into the code, take a look at the recent view--be sure to be very clear about the concept of Web 2.0. When you hear the Word Web 2.0, you should first ask "What is Web 1.0?" "Although you rarely hear about Web 1.0, it actually refers to a traditional web with a completely different request and response model." For example, click a button on the Amazon.com site or enter a search term. A request is sent to the server, and then the response is returned to the browser. This request is not just a list of books and bibliographies, but another complete HTML page. So when a Web browser is redrawn with a new HTML page, you may see flicker or jitter. In fact, you can see the requests and responses clearly from each new page you see.

Web 2.0 (to a large extent) eliminates this visible reciprocating interaction. For example, visit sites such as Google Maps or Flickr (see Resources for links to these support Web 2.0 and Ajax sites). For example, on Google Maps, you can drag the map, zoom in and out, and only a few redraw operations. Of course there are still requests and responses, but they are hidden behind the scenes. As a user, the experience is more comfortable and feels like a desktop application. This new feeling and paradigm is what you realize when someone mentions Web 2.0.

The need to be concerned is how to make these new interactions possible. Obviously, you still need to make requests and receive responses, but it is the HTML redraw that interacts with each request/response that makes for slow, clumsy Web interaction. So it's clear that we need a way to make requests and receive responses that only contain the data that you need rather than the entire HTML page. The only time you need to get the whole new HTML page is when you want the user to see the new page.

Most interactions, however, add details to existing pages, modify body text, or overwrite existing data. In these cases, Ajax and Web 2.0 methods allow data to be sent and received without updating the entire HTML page. For those who often surf the internet, this ability can make your applications feel faster, respond more promptly, and let them visit your site from time to times.

   XMLHttpRequest Introduction

To truly realize this magnificent miracle, you must be very familiar with a JavaScript object, that is, XMLHttpRequest. This small object has actually been in several browsers for some time, and it is the core of Web 2.0, Ajax, and most of the rest of this column that will be introduced in the next few months. To give you a quick overview of it, here are a few of the few methods and properties that will be used for that object.

open (): Creates a new request to the server.

send (): Sends a request to the server.

abort (): Exits the current request.

readystate: Provides the ready state of the current HTML.

ResponseText: The request response text returned by the server.

If you don't know these (or any of them), you don't have to worry about each of the methods and properties in the next few articles. What you should know now is to be clear about what to do with XMLHttpRequest. Note that these methods and properties are related to sending requests and handling responses. In fact, if you see all the methods and properties of XMLHttpRequest, you'll find that they all have to do with very simple request/response models. Obviously, we're not going to encounter a particularly new GUI object or some very mysterious way to create user interaction, and we'll use very simple requests and very simple responses. It doesn't sound like much attraction, but using that object can completely change your application.

   the simple new

First you need to create a new variable and assign it a XMLHttpRequest object instance. This is simple in JavaScript, as long as you use the New keyword for the object name, as shown in Listing 1.

Listing 1. Create a new XMLHttpRequest object


It's not hard, is it? Remember that JavaScript does not require a variable type to be specified, so you do not need to do this as in Listing 2 (this may be required in the Java language).

Listing 2. To create a XMLHttpRequest Java pseudo code

XMLHttpRequest request = new XMLHttpRequest ();

So create a variable with var in JavaScript, give it a name (such as "request"), and then assign it a new XMLHttpRequest instance. You can then use the object in the function.

   Error Handling

In fact all sorts of things can go wrong, and the code above does not provide any error handling. A better approach is to create the object and gracefully exit the problem when it occurs. For example, any older browsers--whether you believe it or not--still use the old version of Netscape Navigator--Do not support XMLHttpRequest, and you need to let these users know that something is wrong. Listing 3 shows how to create the object to emit a JavaScript warning when a problem occurs.

Listing 3. Create a XMLHttpRequest with error handling capabilities


Be sure to understand these steps:

Create a new variable request and assign False value. False is used later as a decision condition, which indicates that the XMLHttpRequest object has not yet been created.

• Add Try/catch Block:

• Try to create a XMLHttpRequest object.

1. Failure (catch (failed)) guarantees that the value of the request is still false.

2, check whether the request is still false (if everything is normal will not be false).

• Use JavaScript warnings to notify users of problems if a problem occurs (request is false).

The code is very simple, and for most JavaScript and WEB developers, it takes longer to really understand it than to read and write code. You have now got a XMLHttpRequest object creation code with error checking and can tell you where the problem is.

deal with Microsoft

Everything seems to be fine, at least before experimenting with Internet Explorer. If you do this, you will see the bad situation shown in Figure 1.


Figure 1. Internet Explorer reports an error



Clearly something is wrong, and Internet Explorer is hardly an outdated browser because 70% of the world uses Internet Explorer. In other words, if Microsoft and Internet Explorer are not supported, it will not be welcomed by the WEB world! So we need to work with Microsoft browsers in a different way.

It was verified that Microsoft supports Ajax, but its xmlhttprequest version has a different name. In fact, it calls it a few different things. If you are using a newer version of Internet Explorer, you need to use object Msxml2.xmlhttp, while older versions of Internet Explorer use Microsoft.XMLHTTP. We need to support both types of objects (while also supporting non-Microsoft browsers). Take a look at listing 4, which adds support for Microsoft on the basis of the aforementioned code.

   has Microsoft been involved?

There have been a number of articles on Ajax and Microsoft's growing interest and involvement in this area. In fact, it is said that Microsoft's latest version of Internet Explorer--version 7.0, which will be launched in the second half of 2006, will begin to support XMLHttpRequest directly, allowing you to replace all MSXML2 with the new keyword. XMLHTTP create code. But don't get too excited and still need to support older browsers, so cross-browser code won't disappear quickly.


Listing 4. Increase support for Microsoft browsers


It's easy to be fascinated by these curly braces, so each step is described below:

• Create a new variable request and assign False value. Using false as a criterion, it indicates that the XMLHttpRequest object has not yet been created.

• Add Try/catch Block:

1, try to create the XMLHttpRequest object.

2. If failed (catch (Trymicrosoft)):

1 try to create a Microsoft-compatible object (MSXML2.XMLHTTP) using a newer version of Microsoft Browser.

2 If a failure (catch (Othermicrosoft)) attempts to create a Microsoft-compatible object (Microsoft.XMLHTTP) using an older version of Microsoft Browser.

3) If the failure (catch (failed)) guarantees that the request's value is still false.

• Check that the request is still false (not false if all goes well).

• Use JavaScript warnings to notify users of problems if a problem occurs (request is false).

After you modify the code and then use the Internet Explorer experiment, you should see the form you have created (no error messages). The results of my experiment are shown in Figure 2.


Figure 2. Internet Explorer is working properly

   Static and dynamic

Take a look at listings 1, 3, and 4, and note that all of this code is directly nested within the script tag. JavaScript code such as this not put into a method or function body is called static JavaScript. This means that the code runs some time before the page is displayed to the user. (although it is not possible to know exactly how the code will function when it is run according to the specification, it can be guaranteed to run before the user can interact with the page.) This is also a common way for most Ajax programmers to create XMLHttpRequest objects.

That is, you can also put the code in one method, as in Listing 5.

Listing 5. To move the XMLHttpRequest creation code into a method


If you write code this way, you need to call the method before you handle Ajax. So you'll need code like listing 6.

Listing 6. Using the XMLHttpRequest creation method


The only problem with this code is the delay in error notification, which is why most Ajax programmers do not use this approach. Suppose a complex form has 10 or 15 fields, a selection box, and so on, to activate some Ajax code when the user enters text in the 14th field, from top to bottom in the form order. At this point the GetCustomerInfo () is run to try to create a XMLHttpRequest object, but (for this example) it fails. A warning is then displayed to the user, telling them explicitly that they cannot use the application. But the user has spent a lot of time typing data into the form! This is very annoying and annoying and obviously won't attract users to visit your site again. If you use static JavaScript, users will quickly see the error message when they click on the page. It's annoying, isn't it? It may make the user mistakenly think that your WEB application cannot run on his browser. But, of course, it's better to show the same error than when they've spent 10 minutes typing in the information. Therefore, I recommend that you write static code that allows users to discover problems as early as possible.

send request with XMLHttpRequest

After you get the request object, you can enter the request/response loop. Remember, the only purpose of XMLHttpRequest is for you to send requests and receive responses. Everything else is the work of JavaScript, CSS, or other code on the page: Changing the user interface, switching images, and interpreting the data returned by the server. Once you are ready to XMLHttpRequest, you can send the request to the server.

   Welcome to use the sandbox

Ajax uses a sandbox security model. Therefore, Ajax code (specifically the XMLHttpRequest object) can only send requests to the same domain in which it resides. Security and Ajax will be introduced further in future articles, so just know that code running on the local machine can only send requests to server-side scripts on the local machine. If you have Ajax code running on www.breakneckpizza.com, you must send the request www.breakneck.com the script that is running in.

   Set Server URL

The first step is to determine the URL of the connected server. This is not a special requirement for Ajax, but it is still necessary to establish a connection, and you should now know how to construct the URL. Most applications construct the URL in combination with some static data and data from the user-processed form. For example, the JavaScript code in Listing 7 gets the value of the phone number field and constructs the URL.

Listing 7.1 establishes the request URL


Listing 7.2 establishing a compatible IE7.0 request


There is no place that is difficult to understand. First, the code creates a new variable phone and assigns the value of the form field with ID "phone" to it. Listing 8 shows the XHTML for this form, where you can see the phone field and its id attribute.

Listing 8. Break Neck Pizza Form




Enter your phone number:


Your order is delivered to:



Type your order in:






Also note that when a user enters a phone number or changes the phone number, the GetCustomerInfo () method shown in Listing 8 is triggered. This method obtains the phone number and constructs a URL string stored in the URL variable. Remember, because Ajax code is sandbox-type, you can only connect to the same domain, and you don't actually need a domain name in the URL. The script in this example is named/cgi-local/lookupcustomer.php. Finally, the phone number is appended to the script as a Get parameter: "phone=" + Escape (phone).

If you have never seen the Escape () method before, it is used to escape any character that cannot be sent correctly in clear text. For example, the spaces in the phone number will be converted to the character% 20, allowing these characters to be passed in the URL.

You can add as many parameters as you want. For example, if you need to add another parameter, just attach it to the URL and separate it with the (&) character [the first argument is separated by a question mark (?) and a script name].

   Open Request

When you have a URL to connect to, you can configure the request. You can do this by using the open () method of the XMLHttpRequest object. The method has five parameters:

Request-type: The type of request sent. A typical value is a get or POST, but a head request can also be sent.

URL: The URL to connect to.

Asynch: True if you want to use an asynchronous connection, false otherwise. The parameter is optional and the default is true.

Username: If authentication is required, you can specify the user name here. The optional parameter has no default value.

Password: If authentication is required, you can specify a password here. The optional parameter has no default value.

The first three parameters are usually used. In fact, you should specify that the third argument is "true" even if an asynchronous connection is required. This is the default value, but it is easier to understand whether the request is asynchronous or synchronous.

By combining these, you usually get a line of code as shown in Listing 9.

Open () is it on?

Internet developers do not agree on exactly what the open () method does. But it doesn't actually open a request. If you monitor the network and data transfer between the Xhtml/ajax page and its connection scripts, you will not see any traffic when you call the open () method. It is not clear why the name was chosen, but it is clearly not a good choice.


Listing 9. Open Request

function GetCustomerInfo () {
var phone = document.getElementById ("Phone"). Value;
var url = "/cgi-local/lookupcustomer.php?phone=" + Escape (phone);
Request.open ("Get", url, True);
}

Once the URL is set, the other is simple. Most requests use get is enough (in a later article will see the need to use POST), plus the URL, which is the use of the open () method all the required.

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.