Master AJAX, Part 2: Send asynchronous requests with JavaScript and Ajax ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ -------------------------------------------------- ------------------------------ published: 2006-04-18 09:04:32 author: Brett McLaughlin source: ibm Language: Chinese Reading: 332 Phase IPAs' Previous Articles (see links in the reference), we introduced the Ajax application to investigate the basic concepts of promoting the AJAX application. The core is a lot of technology you may have already understood: JavaScript, HTML, and XHTML, a little dynamic HTML and DOM (document object model). This article will enlarge a little, put your eyes on the specific AJAX details. In this article, you will begin contact with the most basic and basic objects and programming methods for Ajax: XMLHttpRequest objects. This object is actually just a common thread across all Ajax applications, which may have been expected that only thorough understanding the object to give full play to the potential of programming. In fact, sometimes you will find that XMLHTPREQUEST is not possible to use XMLHttpRequest correctly. What has actually happened? Web 2.0 glances first to see the nearest view before deep research code - must be very clear about Web 2.0. When I heard the word Web 2.0, I should first ask "What is WEB 1.0?" Although few listening to people mentioned Web 1.0, it is actually a traditional web that has a completely different request and response model. For example, click on a button or enter the search term on the Amazon.com website. Just send a request to the server, then return to the browser. This request is not just a list of books and books, but another complete HTML page. Therefore, when the web browser is redrawged with the new HTML page, it may be blinking or jitter. In fact, the request and response can be clearly seen by seeing each new page. Web 2.0 (to a large extent) eliminates this visible reciprocal interaction. For example, access to Google Maps or Flickr (see Resources) for these supports Web 2.0 and AJAX sites. For example, on Google Maps, you can drag maps, zoom in, and shrink, only few redraw operations. Of course, there is still a request and response here, but it is only hidden behind the scenes. As a user, the experience is more comfortable, it feels like a desktop app. This new feeling and model is that when someone mentioned Web 2.0 you experience. What you need to care is how to make these new interactions. Obviously, it is still necessary to issue a request and reception response, but it is the feeling of slow, clumsy web interaction, which is a slow, clumsy web interaction. So it is clear that we need a way to make the request and the received response contain only the required data instead of the entire HTML page. The only need to get the entire new HTML page, you want users to see the new page. However, most interactions add details on existing pages, modify the main text or overwrite the original data. In these cases, AJAX and Web 2.0 methods allow for sending and receiving data without updating the entire HTML page. For those who are often online, this ability allows your app to feel faster, respond more timely, let them visit your website from time to time.
XMLHTTPREQUEST Introduction To truly implement this beautiful miracle, you must be very familiar with a JavaScript object, namely XMLHttpRequest. This little object is actually existed in several browsers. It is the core of Web 2.0, Ajax, and most other contents to be introduced in the next few months. In order for you to know it quickly, the following will give a few ways and properties that will be used for this object. Open (): Create a new request to the server. Send (): Sends a request to the server. Abort (): Exit the current request. ReadyState: Provides the current HTML ready state. ResponseText: The request responded to the server returned. If you don't understand these (or any one of them), you don't have to worry, we will introduce each method and attribute in the following articles. What should I know now is to make anything to do with XmlhttpRequest. Note that these methods and properties are related to the send requests and process responses. In fact, if all methods and properties of XMLHttpRequest are seen, they will find that they are related to very simple request / response models. Obviously, we will not encounter a very new GUI object or a certain ultrabic mysterious way to create a user interaction, we will use a very simple request and a very simple response. It seems that there is not much attractive, but the object can completely change your app. Simple NEW first needs to create a new variable and assign it an XMLHttpRequest object instance. This is very simple in JavaScript, as long as the NEW keyword is used, as shown in Listing 1. Listing 1. Creating a new XMLHttpRequest object
Var Request = new xmlhttpRequest ();
script>
Is it not difficult? Remember, JavaScript does not require a specified variable type, so it is not necessary to do like Listing 2 (like this in the Java language). Listing 2. Creating XMLHttpRequest Java pseudo code
XMLHTTPREQUEST REQUEST = New XMLHTTPREQUEST ();
So create a variable in JavaScript to create a variable to give it a name (such as "request") and then gives it a new XMLHttpRequest instance. This object can be used in the function later. Error handling is incorrect in actually various things, and the above code does not provide any error handling. A preferred way is to create this object and exit elegant when there is a problem. For example, any earlier browser (whether you believe, still someone in using the old version of Netscape Navigator) does not support XMLHttpRequest, you need to let these users know that there is a problem. Listing 3 shows how to create this object so as to issue a JavaScript warning when there is a problem. Listing 3. Creating XMLHttpRequest with error handling power
Var Request = false;
Try {
Request = new xmlhtpRequest ();
} catch (failed) {
REQUEST = FALSE;
}
IF (! request)
Alert ("Error Initializing XMLHttpRequest!");
script>
Be sure to understand these steps:
Create a new variable Request and assign a value false. Later, False will be used as a decision condition, which indicates that the XMLHttpRequest object has not yet created. Add TRY / CATCH block:
Try to create an XMLHttpRequest object. If the catch (failed) is guaranteed, the value of Request is still false. Check if the request is still false (if everything is normal, it will not be false). If a problem occurs (Request is false), use the JavaScript warning to notify the user to have problems. The code is very simple. For most JavaScript and web developers, it really understands it longer than the read and write code. I have already got a period of XMLHttpRequest object with an error check, you can also tell you where there is a problem. It seems good to meet all good, at least before it is used to test these code with Internet Explorer. If you do this, you will see the bad situation shown in Figure 1. Figure 1. Internet Explorer report error
Is Microsoft participated? About Ajax and Microsoft have introduced many articles on the growing interest and participation of this area. In fact, it is said that Microsoft's latest version of Internet Explorer - Version 7.0 will be introduced in the second half of 2006 - will start directly to support XMLHttpRequest so you use the New keyword instead of all MSXML2.xmlhttp creation code. But don't be too excited, still need to support the old browser, so crossing the browser code will not disappear quickly. Obviously, it is difficult to say, and Internet Explorer is difficult to say is an outdated browser because 70% of the world are using 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 use different ways to process Microsoft browsers. It is verified that Microsoft supports AJAX, but its XMLHttpRequest version has different names. In fact, it is called several different things. If you use a newer version of Internet Explorer, you need to use object MSXML2.XMLHTTTTTTP, while the older version of Internet Explorer uses Microsoft.xmlhttp. We need to support these two object types (also support non-Microsoft browser). Take a look at the list 4, which adds support for Microsoft on the basis of the aforementioned code. Listing 4. Add support for Microsoft browsers
Var Request = false;
Try {
Request = new xmlhtpRequest ();
} catch (trymicrosoft) {
Try {
Request = New ActiveXObject ("msxml2.xmlhttp");
} catch (osthermicrosoft) {
Try {
Request = New ActiveXObject ("Microsoft.xmlhttp");
} catch (failed) {
REQUEST = FALSE;
}
}
}
IF (! request)
Alert ("Error Initializing XMLHttpRequest!");
script>
It is easy to be fascinated by these flower brackets, so the following introduces each step:
Create a new variable Request and assign a value false. Using False as a judgment condition, it indicates that the XMLHttpRequest object has not been created yet. Add TRY / CATCH block:
Try to create an XMLHttpRequest object. If it fails (Catch (trymicrosoft):
Try to create a Microsoft Compatible Object (MSXML2.xmlHTTP) with a newer version of the Microsoft Browser. If you fail (OtherMicrosoft) attempts to create Microsoft.xmlhttp using the older version of Microsoft Browser. If the catch (failed) is guaranteed, the value of Request is still false. Check if the request is still false (if everything is going well, it will not be false). If a problem occurs (Request is false), use the JavaScript warning to notify the user to have problems. After modifying the code, use the Internet Explorer test, you should see a form that has been created (there is no error message). The results of my experiment are shown in Figure 2. Figure 2. Internet Explorer normal working static and dynamic to see Listing 1, 3 and 4, note that all of these code is directly nested in the Script tag. JavaScript code like this or a function body is called static JavaScript. That is, the code is running at some time before the page is displayed. (Although the code does not fully accurately know how this code has an impact on the browser according to the specification, it can ensure that these codes can run before the user can interact with the page.) This is also a general way for most Ajax programmers to create an XMLHttpRequest object. That is, it is also possible to put these code in a method like a list 5. Listing 5. Move XMLHTTPREQUEST to move to the method
Var Request;
Function creterequest () {
Try {
Request = new xmlhtpRequest ();
} catch (trymicrosoft) {
Try {
Request = New ActiveXObject ("msxml2.xmlhttp");
} catch (osthermicrosoft) {
Try {
Request = New ActiveXObject ("Microsoft.xmlhttp");
} catch (failed) {
REQUEST = FALSE;
}
}
}
IF (! request)
Alert ("Error Initializing XMLHttpRequest!");
}
script>
If you write a code in this way, you need to call the method before processing Ajax. Therefore, you also need a list of this list 6. Listing 6. Creating methods using XMLHttpRequest
Var Request;
Function creterequest () {
Try {
Request = new xmlhtpRequest ();
} catch (trymicrosoft) {
Try {
Request = New ActiveXObject ("msxml2.xmlhttp");
} catch (osthermicrosoft) {
Try {
Request = New ActiveXObject ("Microsoft.xmlhttp");
} catch (failed) {
REQUEST = FALSE;
}
}
}
IF (! request)
Alert ("Error Initializing XMLHttpRequest!");
}
Function getcustomerinfo () {
CreateRequest ();
// Do Something with The Request Variable
}
script>
The only problem of this code is to postpone the error notification, which is why most Ajax programmers do not use this method. Assuming a complex form has 10 or 15 fields, select box, etc. When the user enters text when entering the text in the 14th field (following the form order from top to bottom), some AJAX code is activated. At this time, run the getCustomerInfo () try to create an XMLHttpRequest object, but (for this case) failed. Then displays a warning to the user, which clearly tells them that the application cannot be used. But users have spent a lot of time to enter data in the form! This is very annoying, and hate obviously will not attract users to visit your website again. If you use static JavaScript, you will see the error message soon when you click on the page. This is also annoying, is it? It may make users mistakenly think that your web application cannot run on his browser. However, of course, it is better to show the same mistake after 10 minutes of entering information. Therefore, I recommend writing static code to let users find problems as early as possible.
The request / response loop can be entered after sending the request object with XMLHttpRequest to get the request object. Remember, XMLHttpRequest's only purpose is to let you send requests and reception responses. Everything else is the job of other code in JavaScript, CSS or page: changing the user interface, switching images, explaining the data returned by the server. Once you are ready to XMLHTTPREQUEST, you can send a request to the server. Welcome to the sandbox AJAX adopt a sandbox safety model. Therefore, AJAX code (specifically the XMLHttpRequest object) can only send a request to the same domain. Safe and Ajax will be further introduced in later articles, and now you know the code that is running on the local machine can only send a request to the server-side script on the local machine. If the Ajax code is run on www.breakneckpizza.com, you must send a request in www.breakneck.com. Setting the server URL first to determine the URL of the connected server. This is not a special requirement for Ajax, but it is still necessary, it is obvious that now you should know how to construct the URL. This URL is constructed in most applications in conjunction with some static data and data in a form of user processing. For example, the JavaScript code in Listing 7 obtains the value of the phone number field and constructs the URL. Listing 7. Establishing request URL
Var Request = false;
Try {
Request = new xmlhtpRequest ();
} catch (trymicrosoft) {
Try {
Request = New ActiveXObject ("msxml2.xmlhttp");
} catch (osthermicrosoft) {
Try {
Request = New ActiveXObject ("Microsoft.xmlhttp");
} catch (failed) {
REQUEST = FALSE;
}
}
}
IF (! request)
Alert ("Error Initializing XMLHttpRequest!");
Function getcustomerinfo () {
Var phone = document.getlementByid ("Phone"). Value;
VAR URL = "/cgi-local/lookupcustomer.php?phone=" escape (phone);
}
script>
There is no difficulty here. First, the code creates a new variable phone and assigns it to the value of the ID field of the ID "Phone". Listing 8 shows the XHTML of this form, which can see the Phone field and its ID attribute. Listing 8. Break neck pizza form
p>