One of the interesting things about the basics of the XMLHttpRequest object is that these basics are actually basic. Only a few parameters and a few lines of code separate the synchronous from the asynchronous. When you understand that, not much is required to change a synchronous application into an asynchronous application. Don't believe me? Take a look at the XMLHttpRequest object's properties and methods shown in Table 7-1.
Table 7-1. XMLHttpRequest Object Properties and Methods Method/Property
Description
abort()
Terminates the previous outstanding request.
getAllResponseHeaders()
Returns all response headers, labels, and values, as a string.
getresponseHeader("label")
Returns the value for the provided label.
open("method","url", asynchronous,"username","password")
Opens/assigns a method: GET or POST and, optionally, an asynchronous indicator.
send(content)
Sends the request with optional content. This content can be either a string or DOM data.
setRequestHeader ("label","value")
Sets a request header label/value pair.
onreadystatechange
Event handler for asynchronous requests; fires on each change to the readyState property.
readyState
Status of the request as an integer.
0 = uninitialize
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText
String returned from the server.
responseXML
XML document returned from the server.
status
HTTP response code returned from the server.
statusText
String message associated with the HTTP a.
Right now, the XMLHttpRequest object might seem like a pile of unrelated parts, but when the individual parts are assembled in the correct sequence, things are different. To prove my point, let's take a look at the JavaScript that uses XMLHTTP to synchronously get a file from the server in Gecko-based browsers such as Firefox, Mozilla, and Flock (see Listing 7-1).
Listing 7-1. Getting a File Synchronously
var objXMLHTTP = new XMLHttpRequest();
objXMLHTTP.open('GET', 'books.xml', false);
objXMLHTTP.send(null);
var objXML = objXMLHTTP.responseXML;
The first step is to create an instance of the XMLHttpRequest object using the JavaScript new operator. Next, the open method is invoked using the request method, GET, a destination URL, and a Boolean indicating that the request is not asynchronous. The third and final step is to invoke the send method and assign the responseXML, an XML document, to a variable. And if you're not interested in using XML, there is always the responseText property.



0 comments:
Post a Comment