|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Creating a Simple AJAX LibraryYou should be aware by now that AJAX requests can be a bit complex. To make things easier, you can create an AJAX library. This is a JavaScript file that provides functions that handle making a request and receiving the result, which you can reuse any time you need AJAX functions. This library will be used in the two examples later this hour. Listing 17.1 shows the complete AJAX library. Listing 17.1. The AJAX Library
The following sections explain how this library works and how to use it. The ajaxRequest() FunctionThe ajaxRequest() function handles all of the steps necessary to create and send an XMLHttpRequest. First, it creates the XMLHttpRequest object. This requires a different command for different browsers, and will cause an error if the wrong one executes, so TRy and catch are used to create the request. First the standard method is used, and if it causes an error, the ActiveX method is tried. If that also causes an error, the ajaxreq variable is set to false to indicate that AJAX is unsupported. The ajaxResponse() FunctionThe ajaxResponse() function is used as the onreadystatechange event handler. This function first checks the readyState property for a value of 4. If it has a different value, the function returns without doing anything. Next, it checks the status property for a value of 200, which indicates the request was successful. If so, it runs the function stored in the ajaxCallback variable. If not, it displays the error message in an alert box. Using the LibraryTo use this library, follow these steps:
The two remaining examples in this hour make use of this library to create AJAX applications. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |