Most Web applications use the request/Response Model to obtain the complete HTML page from the server. It is often a process of repeatedly clicking a button, waiting for the server to respond, then clicking another button, and then waiting. With Ajax and XMLHttpRequest objects, you can use the request/response model that does not have users waiting for server response. In this article, Brett McLaughlin describes how to create XMLHttpRequest instances that adapt to different browsers, create and send requests, and respond to servers.
In this article, you will begin to access all the basic and basic Ajax objects and programming methods: XMLHttpRequest objects. This object is actually a public thread that spans all Ajax applications. As you may have expected, only a thorough understanding of this object can give full play to the potential of programming. In fact, you may find that XMLHttpRequest cannot be used to correctly use XMLHttpRequest. What the hell is going on?
Web 2.0 glance
Before going into the code, let's take a look at our recent point of view-we must 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 few people mentioned Web 1.0, it actually refers to the traditional Web with completely different request and response models. For example, click a button on the Amazon.com website or enter a search item. Then a request is sent to the server, and the response is returned to the browser. This request is not only a list of books and bibliography, but also a complete HTML page. Therefore, when a Web browser redraws an HTML page with a new one, it may see flashes or jitters. In fact, the request and response are clearly displayed on each new page.
Web 2.0 (to a large extent) eliminates this visible reciprocating interaction. For example, you can access websites such as Google Maps or Flickr. For example, on Google Maps, you can drag a map, zoom in and out, with only a few repainting operations. Of course, there are still requests and responses, but they are all hidden behind the scenes. As a user, the experience is more comfortable and feels like a desktop application. This new feeling and pattern is what you feel when someone mentions Web 2.0.
You need to be concerned about how to make these new interactions possible. Obviously, requests and responses still need to be sent, but it is the HTML re-painting of each request/response interaction that results in a slow and clumsy Web interaction. Therefore, it is clear that we need a method to make the sent request and received response only contain the required data, rather than the entire HTML page. The only time you need to get the entire HTML page is when you want the user to see the new page.
However, most interactions include adding details, modifying the subject text, or overwriting the original data on an existing page. In these cases, the Ajax and Web 2.0 methods allow sending and receiving data without updating the entire HTML page. For those who frequently access the Internet, this capability can make your applications feel faster and respond more timely, so that they can patronize your website from time to time.
Introduction to XMLHttpRequest
To realize such a brilliant miracle, you must be very familiar with a JavaScript Object, XMLHttpRequest. This small object has actually existed in several browsers for a while. It is the core of Web 2.0, Ajax, and most other content to be introduced in the next few months of this column. To help you quickly understand the object in a large scale, the following describes a few methods and attributes that will be used for this object.
- Open (): Create a new request to the server.
- Send (): send a request to the server.
- Abort (): exit the current request.
- ReadyState: Provides the ready status of the current HTML.
- ResponseText: Request Response text returned by the server.
If you do not understand this (or any of them), you don't have to worry about it. In the following articles, we will introduce each method and attribute. Now we should understand what to do with XMLHttpRequest. Note that these methods and attributes are related to sending requests and processing responses. In fact, if you see all the methods and attributes of XMLHttpRequest, you will find that they are related to a very simple request/response model. Obviously, we will not encounter a very new GUI object or a super mysterious method for creating user interaction. We will use very simple requests and very simple responses. It does not seem attractive, but using this object can completely change your application.
Simple new
Create a new variable and assign it an XMLHttpRequest object instance. This is simple in JavaScript. You only need to use the new keyword for the object name, as shown in Listing 1.
Listing 1. Creating a New XMLHttpRequest object
<script language="javascript" type="text/javascript"> var request = new XMLHttpRequest(); </script>
|
Not hard? Remember, JavaScript does not need to specify the variable type, so it does not need to be done as in Listing 2 (this may be required in Java ).
Listing 2. Creating Java pseudocode for XMLHttpRequest
XMLHttpRequest request = new XMLHttpRequest();
|
Therefore, create a variable in JavaScript using var, give it a name (such as "request"), and then assign it a new XMLHttpRequest instance. Then you can use this object in the function.
Error Handling
In fact, all kinds of things may go wrong, and the above Code does not provide any error handling. A better way is to create this object and exit gracefully when a problem occurs. For example, any earlier browser (whether or not you believe that someone is still using the old version of Netscape Navigator) does not support XMLHttpRequest. You need to let these users know that something is wrong. Listing 3 describes how to create an object so that a JavaScript warning is triggered when a problem occurs.
Listing 3. Creating XMLHttpRequest with error processing capability
<script language="javascript" type="text/javascript"> var request = false; try { request = new XMLHttpRequest(); } catch (failed) { request = false; } if (!request) alert("Error initializing XMLHttpRequest!"); </script>
|
Be sure to understand these steps:
1. Create a new variable request and assign a value of false. False is used as the criterion for determining whether an XMLHttpRequest object has been created.
2. Add try/catch blocks:
Create an XMLHttpRequest object.
If the request fails (catch (failed), make sure that the request value is still false.
3. Check whether the request is still false (if everything is normal, it will not be false ).
4. If a problem occurs (request is false), use JavaScript to warn users of a problem.
The code is very simple. For most JavaScript and Web developers, it takes longer to really understand it than to read and write code. Now we have a piece of XMLHttpRequest object creation code with an error check, and can tell you where the problem has occurred.
Microsoft
It seems that everything works well, at least before you try the Code with Internet Explorer. If you do this experiment, you will see the bad situation shown in Figure 1.
Figure 1. Internet Explorer reports an error
Obviously something is wrong, and Internet Explorer is hardly an outdated browser, because 70% of the world is using Internet Explorer. In other words, if Microsoft and Internet Explorer are not supported, they will not be welcomed by the Web world! Therefore, we need to use different methods to process Microsoft browsers.
It is verified that Microsoft supports Ajax, but its XMLHttpRequest version has different names. In fact, it calls it something different. If you use a newer version of Internet Explorer, you need to use the Msxml2.XMLHTTP object, while the older version of Internet Explorer uses Microsoft. XMLHTTP. We need to support these two object types (and also support non-Microsoft browsers ). See Listing 4, which adds support for Microsoft based on the preceding code.
Listing 4. Added support for Microsoft browsers
<script language="javascript" type="text/javascript"> var request = false; try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = false; } } } if (!request) alert("Error initializing XMLHttpRequest!"); </script>
|
The eyes are easily fascinated by these curly braces, so each step is described below:
1. Create a new variable request and assign a value of false. False is used as the judgment condition, indicating that the XMLHttpRequest object has not been created.
2. Add try/catch blocks:
- Create an XMLHttpRequest object.
- If it fails (catch (trymicrosoft )):
1) try to create a Microsoft compatible object (Msxml2.XMLHTTP) with a newer Microsoft browser ).
2) If catch (othermicrosoft) fails, try to create a Microsoft-compatible object (Microsoft. XMLHTTP) in a later version of Microsoft browser ).
- If the request fails (catch (failed), make sure that the request value is still false.
3. Check whether the request is still false (if everything goes well, it will not be false ).
4. If a problem occurs (request is false), use JavaScript to warn users of a problem.
In this way, after modifying the code and then using Internet Explorer for testing, you should see the created form (no error message ). The results of my experiment are shown in figure 2.
Figure 2. Internet Explorer works properly