
APPENDIX A ■ ■ ■ The XMLHttpRequest Object More often than not, chances are you will use some sort of library to do your Ajax work. Some of the libraries out there—only a handful of which we talked about in this book—really do make it far easier to work the “Ajax way.” That being said, there are times when you will want to go “bare metal,” so to speak, and use the XMLHttpRequest object yourself. In those instances, this appendix will be an invaluable aid to you. What Is the XMLHttpRequest Object? XMLHttpRequest is an object (an ActiveX object in Microsoft Internet Explorer, a native component in most other browsers) that allows a web page to make a request to a server and get a response back without reloading the entire page. The user remains on the same page, and more important, they will not actually see the processing occur—that is, they will not see a new page loading, not by default at least. Using the XMLHttpRequest object makes it possible for a developer to alter a page previously loaded in the browser with data from the server without having to request the entire page from the server again. What Browsers Support the XMLHttpRequest Object? XMLHttpRequest is present in Internet Explorer 5.0 and higher, Apple’s Safari 1.2 and higher, Mozilla’s Firefox 1.0 and higher, Opera 7.6 and higher, and Netscape 7 and higher. Other browsers may or may not support it, so you should check for the capability before attempting to use it if you intend to support alternative browsers. Also of note is a little JavaScript library by Andrew Gregory that allows for cross-browser Ajax support without dealing with the details of what browsers support the object and how. There are some limitations, but it is of interest nonetheless. You can find information on it here: www.scss.com.au/family/andrew/webdesign/xmlhttprequest. 479 480 APPENDIX A ■ THE XMLHTTPREQUEST OBJECT Is the XMLHttpRequest Object a W3C Standard? (Or Any Other Kind of Standard for That Matter!) No, the XMLHttpRequest object is not a W3C standard, or a standard of any other standards body. The W3C DOM Level 3 specification’s “Load and Save” capabilities would provide similar functionality, but currently no browsers implement the Level 3 specification. Therefore, until that specification is widely adopted, if you need to send an HTTP request from a browser and get a response from a server, aside from the normal page navigation mechanism, the XMLHttpRequest object is the only viable option, along with some of the lesser-used (nowadays) alternatives like Java applets and ActiveX controls. How Do I Use the XMLHttpRequest Object? In Mozilla, Firefox, Safari, and Netscape, you create an instance of the XMLHttpRequest object by doing the following: <script>var xhr = new XMLHttpRequest();</script> For Internet Explorer: <script> var xhr = new ActiveXObject("Microsoft.XMLHTTP");</script> Here is an example of using the XMLHttpRequest object: <script> var xhr = null; if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if (xhr) { var url = "/someURI"; xhr.onreadystatechange = xhrCallback; xhr.open("get", url, true) xhr.send() } function xhrCallback() { if (xhr.readyState == 4) { if (xhr.status == 200) { alert("Ok"); APPENDIX A ■ THE XMLHTTPREQUEST OBJECT 481 } else { alert("Problem retrieving Ajax response"); } } } </script> XMLHttpRequest Object Method and Properties Reference Tables A-1 and A-2 outline the methods and properties available on the XMLHttpRequest object, representing the full API interface to that object through which you will interact with it. Table A-1. XMLHttpRequest Object Methods Method Description abort() Stops the request that the object is currently processing. Note that like clicking the Stop button in your browser, the server will not be notified and will continue to process the request. getAllResponseHeaders This method returns all of the headers, both keys and values, as a string. getResponseHeader("key") This method returns the specified header value as a string. open("method", "url" [,asyncFlag Contrary to its name, this does not appear to literally [,"username" [,"password"]]] open anything. Instead, it just sets the parameters for the pending request. The value of method may be any valid HTTP method, get and post being the most common. asyncFlag is either true or false. Setting this to false will cause all JavaScript on the page to halt until the request returns. This is generally not desirable because if the server is unavailable, or the operation simply takes a long time, the user interface will seem to freeze to the user. Use with caution! username and password are used to make requests to URLs protected with Basic Auth security. Note that these two parameters, as well as asyncFlag, are optional, while method and url are required. send(content) This method transmits the pending request, and optionally sends a POST body or serialized DOM object (i.e., XML document). If POSTing simple parameters, content should be a string in the form “name1=value1&name2=value2”—in other words, a query string minus the initial question mark. setRequestHeader("key", "value") Sets an HTTP header that will be set on the outgoing response. 482 APPENDIX A ■ THE XMLHTTPREQUEST OBJECT Table A-2. XMLHttpRequest Object Properties Property Description onReadyStateChange This is a pointer to the function that will serve as the event handler for the request this object instance is processing. Note that this function will be called multiple times during the lifecycle of the request. readyState This is an integer representing the status of the request. Possible values are 0 (uninitialized), 1 (loading), 2 (loaded), 3 (interactive), and 4 (complete). responseText This is a textual string version of the response from the server. Even if the response was XML, you will still find the actual text of the response here. responseXML If the response from the server was XML, the object will do the extra work of parsing it and generating a real DOM-compatible object that you can manipulate with DOM methods. status This is the numeric HTTP result code returned by the server, such as 404 if the resource is not found, or 200 if the result was OK. statusText This is a textual message string describing the status code. XMLHttpRequest Object Status Codes Table A-3 lists the status codes that can show up in the readystate field of the XMLHttpRequest object during the lifecycle of a request as your callback function is repeatedly called. Table A-3. XMLHttpRequest Object readystate Status Codes Numeric Code Description 0 Uninitialized. This is the value the readystate field will have initially before any operation is begun. 1 Loading. This means the open() method has been successfully called, but send() has not yet been called. 2 Loaded. This means send() has been called, and the object has completed the request, but no data has been received yet. Headers and status, however, are available at this point. 3 Receiving (or Interactive). This means the response is being chunked back to the client. responseText at this point will hold the response as received thus far. 4 Loaded (or Completed). The request has completed and the full response has been received. APPENDIX B ■ ■ ■ Libraries, Websites, and Books, Oh My! Throughout this book, we’ve referenced a number of libraries, websites, and books for you to get further information or see examples. Here is a concise list of all those references for your convenience, even for those libraries that are used as part of an application but not specifi- cally described (but, uh, please do still read this book, OK?). Libraries/Toolkits/Products • Adobe (formerly Macromedia) Flash (www.adobe.com/products/flash/flashpro): Flash is not just a vector animation tool; it is truly a full-fledged development environment allow- ing you to create multimedia-rich websites that will run identically across most modern platforms (if a supported Flash player is available, which is mostly the case these days). • Adobe (formerly Macromedia) Flex (www.adobe.com/flex): A rich client development framework that can greatly simplify creation of dynamic web applications. • Apache Ant (ant.apache.org): The de facto standard in Java build tools. • Apache Geronimo (geronimo.apache.org): An Apache application server. • Apache Jakarta Commons (jakarta.apache.org/commons): Under the Commons banner you will find a number of very useful libraries, including Commons Logging, BeanUtils, FileUpload, Commons Chain, and much more. In short, if you aren’t using Commons today, you should be tomorrow! • BEA WebLogic (www.bea.com): Another of the big players in the application server mar- ket; provides much the same capabilities as WebSphere (although both vendors have their advantages and disadvantages). • Caucho’s Resin (www.caucho.com): Another application server, fairly popular with web hosts. • Dojo (dojotoolkit.org): A popular Ajax toolkit that, in addition to its Ajax functionality, provides a lot of nifty client-side functions such as collections and client-side session storage, as well as a number of excellent GUI widgets. 483 484 APPENDIX B ■ LIBRARIES, WEBSITES, AND BOOKS, OH MY! • DWR, or Direct Web Remoting (getahead.ltd.uk/dwr): A very popular Ajax library that provides a syntax in JavaScript to call objects on the server, making them appear to be running locally (in terms of the JavaScript you write). • Eclipse (www.eclipse.org): Probably the most popular Java IDE out there, and free to boot! • FreeMarker (freemarker.sourceforge.net): A Java-based template engine, used by default by WebWork. • HSQLDB (www.hsqldb.org): Free, lightweight (but not in terms of functionality!), pure- Java database engine. • IBM WebSphere (www-306.ibm.com/software/websphere): A full-blown Java application server providing many services, including servlets, JSP, JNDI, EJB, and so on.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages25 Page
-
File Size-