This means that the function being called, doAlert in the example given, needs to have a parameter in its definition: function doAlertmyEvent { // do something with the myEvent variable
Trang 1The word true inside the cloneNode() method means that you want to clone the node and all its children In this case it would be the table and all the contents of the table If for some reason you didn’t want to make a copy
of the children, you’d put false there
Once you’ve made your changes, you can replace the original table with the new one using the replaceNode() method Like insertBefore() and
removeChild(), this method is called by the parent of the nodes to be replaced Given the myTable and cloneTable variables defined above, you could do this:
var tableParent = myTable.parentNode;
tableParent.replaceChild(cloneTable, myTable);
Manipulating a Page Using the DOM
As mentioned earlier, you could do most of the things described in this section with creative use of innerHTML However, sometimes dealing with the complex strings needed to get innerHTML to be what you want can be difficult
In these cases, the DOM techniques are very helpful When we get to the chapters on Ajax, you’ll see even more applications of the DOM manipu-lation techniques
Fancy Event Handling
Dynamic web pages call for dynamic reactions to user actions We’ve discussed how to write JavaScript that reacts when users click links, buttons, and form elements Now it’s time to learn about more complicated event handling: how to accurately read the keyboard and the mouse
The event Object
Whenever an event occurs, an event object is generated The nature of this object depends on the event which generated it To access the event object, simply pass the keyword event to whichever function is handling the event:
<a href = "#" onClick = "handleClick(event); return false; ">Click me!</a>
The event object is most frequently accessed when you want to know which key a user has pressed, or precisely where the mouse is
Keyboard Events
There are two main keyboard event handlers, the functions of which are pretty obvious: onKeyDown and onKeyUp Triggering either of these event handlers creates an event object that stores which key has been pressed (or unpressed) and whether or not any special keys (ALT,CTRL, or SHIFT)were pressed at the same time The relevant properties of the event object appear in Table 13-2
Trang 2Figure 13-18 is short script that demonstrates how to use the event object
to determine which key a user has pressed while in a text input field
<html><head><title>Demonstrating Keyboard Events</title>
<script type = "text/javascript">
<! hide me from older browsers
function displayEvent(evt) {
var type = evt.type;
X var code = evt.keyCode;
Y var theChar = String.fromCharCode(code);
var alt = evt.altKey;
var ctrl = evt.ctrlKey;
var shift = evt.shiftKey;
Z var displayString = "event type: " + type + "; key code: " + code +
", which is the character " + theChar +
"; ALT, CTRL, and SHIFT were: " +
alt + ", " + ctrl + ", and " + shift + "\n\n";
[ if ((code >= 65) && (code <= 90)) {
Type here: <input type = "text"
\ onKeyDown = "displayEvent(event);" onKeyUp = "displayEvent(event);"><br> See the events here: <textarea id = "showEvents" cols = "80" rows = "20">
</textarea>
</form>
</body>
</html>
Figure 13-18: Demonstrating keyboard events
Although the script in Figure 13-18 is simple, there are some subtleties First, whenever a user types anything while in the text field, the act of pressing the key down creates one event, and the act of releasing the key creates another event These events are captured by the event handlers in \ In either case, the displayEvent() function is called This function creates variables for each of the event’s properties, combines them into a string, and then puts the
Table 13-2: Properties for Keyboard Events
altKey boolean True if the ALT key was down when this key was pressed ctrlKey boolean True if the CTRL key was down when this key was pressed shiftKey boolean True if the SHIFT key was down when this key was pressed keyCode integer The Unicode decimal value for the key that was pressed; use
String.fromCharChode(keyCode) to convert this to a string Type string The type of event —keyup or keydown, for example
Trang 3resulting string into the textarea with the id of showEvents The most interesting lines in this function are X, which gets a number representing the character being pressed, and Y, which converts that number into an actual character After those lines are executed, Z creates a string representing what happened
in the event and [ puts that string in the text area if the key being pressed is
a letter (letters have character code numbers between 65 and 90)
Figure 13-19 shows what happens when a and then A are typed into the
text field Notice that in both cases, the characterCode is 65, and the resulting
character is A In order to determine whether the user has entered a capital
or lowercase letter, the shiftKey property of the event must be examined
Figure 13-19: Typing a and A into the Figure 13-18 script
Mouse Events
Mouse events have their own properties Unfortunately, some cross-browser differences complicate accessing the position of the mouse and determining which mouse button was clicked Table 13-3 shows the properties of mouse events, and it gives some details about how to deal with cross-browser differences
Table 13-3: Properties of Mouse Events Property Description
button Equals 2 if it’s a right-click—otherwise, it depends on the browser clientX Internet Explorer’s X position for the mouse
clientY Internet Explorer’s Y position for the mouse pageX Most other browsers’ X position for the mouse pageY Most other browsers’ Y position for the mouse
Trang 4As you can see from Table 13-3, all the properties of mouse events are browser dependent The button property, for example, describes which button was clicked when an onMouseDown or onMouseUp event happened However, the meaning of the numbers provided by the button property depend on the browser being used In Internet Explorer, 1 means the left button was clicked,
2 means the right button, and 4 means the middle button In most other browsers, 0 means the left button, 1 means the middle button, and 2 means the right button Because 2 means the right button was clicked in both cases and many people don’t have a middle button on their mouse, it is often safe to see if the button property of the event was 2 and call it a left-click if it was not.The position of the mouse is a bit trickier Browsers other than Internet Explorer generally use an event’s pageX and pageY properties to give a number representing the X and Y positions (in pixels) of the event relative to the top-left corner of the browser window These two properties take into con-sideration scrolling a window If a window is 10,000 pixels long and the user has scrolled down to the very bottom, the pageY property will be around 10,000 at the bottom of the window Internet Explorer, on the other hand, uses properties named clientX and clientY These properties do not take scrolling into consideration, so to use them, you should add numbers repre-senting how far down and to the left the browser has been scrolled Those numbers are available as document.body.scrollTop and document.body.scrollLeft.Figure 13-20 presents a script that determines the X and Y positions of a mouse and puts the results in a textarea
<html><head><title>Checking Mouse Position</title>
<script type = "text/javascript">
<! hide me from older browsers
Trang 5In Figure 13-20, moving inside the div calls the displayEvent() function (]), and moving the mouse onto the div clears the textarea that stores all the mouse information collected (^) The displayEvent() function first checks
to see if the browser knows about the pageX property of the event (X) If so it uses pageX to get the x coordinate of the mouse, relative to the top-left corner
of the browser window (Y) and pageY to get the y coordinate If the browser
does not know about the pageX property but does know about the clientX
property (Z), it uses clientX and clientY Notice in [ that the amount that the browser has been scrolled to the right or down must be added to the
clientX and clientY property to account for scrolled windows The last line
in the function (\) adds the appropriate information to the textarea with theidof results
Adding Event Handlers Using JavaScript
Throughout this book, whenever we have wanted to trigger an event based
on a user’s behavior, we have put an event handler inside the triggering element For example, in Chapter 4, when we wanted an alert box to pop up when a user clicked a link, we put an onClick event inside the link:
<a href = "#" onClick = "alert('Thanks!');">Click me</a>
Putting event handlers inside the elements that trigger the events can cause some problems:
z Doing so puts JavaScript inside your HTML elements rather than inside
<script> tags This means that someone trying to understand your JavaScript (and that person may be you) will have to hunt around in the HTML to find all the various bits of JavaScript on the page
z Sometimes you want a JavaScript function to be triggered by many ments For example, if you have 20 checkboxes, each of which has an
ele-onClick, you will need to stick the same code (onClick = "doFunction();")
in 20 different places If the function’s name changes, or if you decide
to add a parameter to the function, you will need to change the page in
For these reasons, modern browsers provide ways for JavaScript to attach functions to the event handlers of objects The template for this is:
element.handler = function;
Trang 6For example, to call a function named doAlert() whenever a div with theid of myDiv is clicked, use the following line:
document.getElementById("myDiv").onclick = doAlert;
This line is unusual for two reasons First, the event handler (onClick)
is all lowercase This is a requirement when assigning a function to a handler
in this way Second, notice that the function does not have parentheses after
it This means that no parameters may be passed to this function However,
a function called in this way does have access to the event that called the function, and it turns out that the event is almost always the only parameter you need
As with all things related to events, there are some browser bilities involved with getting access to the event object In Internet Explorer, the event is automatically stored in a variable named event To access the event, just use the event variable:
incompati-function doAlert() {
myEvent = event;
// do something with the myEvent variable
alert("Got the event!");
}
In most other browsers, the event is automatically passed as a parameter
to the function being called This means that the function being called,
doAlert() in the example given, needs to have a parameter in its definition:
function doAlert(myEvent) {
// do something with the myEvent variable
alert("Got the event!");
}
Once the event object has been accessed inside a function, it is sometimes helpful to retrieve information about the object that created the event To do this, Internet Explorer uses an event object property called srcElement Most other browsers use a property named target
Figure 13-21 puts all this information together in a cross-browser script for assigning functions to events using JavaScript
<html><head><title>Cross-Browser Event Handling</title>
<script type = "text/javascript">
<! hide me from older browsers
function attachHandlers() {
X var theElements = document.getElementById("myForm").childNodes;
for (var loop = 0; loop < theElements.length; loop++) {
Trang 7} // show me >
</script>
</head>
^ <body onLoad = "attachHandlers();">
<form id = "myForm">
_ <input type = "checkbox" name = "1"><input type = "checkbox" name = "2">
<input type = "checkbox" name = "3"><br>
<input type = "checkbox" name = "4"><input type = "checkbox" name = "5">
<input type = "checkbox" name = "6"><br>
</form>
</body>
</html>
Figure 13-21: Cross-browser script for attaching functions to event handlers
The script in Figure 13-21 creates a set of six checkboxes, each with a different name Clicking any of these checkboxes results in an alert box pro-viding the name of the checkbox that was just clicked Notice that the HTML describing the checkboxes contains no onClick handlers (_) This is because the handlers are assigned using JavaScript The onLoad handler inside the
<body> tag (^) triggers the function which assigns the handlers The function
is called by the onLoad handler because an HTML element cannot have a tion attached to its handler until the web browser knows about the element
func-If a piece of JavaScript tries to attach a handler to a form element that has not yet been processed by the browser, an error will result For this reason, it’s best to wait until all the elements have been loaded before assigning functions to their handlers
TheattachHandlers() function has several interesting aspects First, it uses the DOM methods covered earlier in the chapter to access the checkboxes These checkboxes are child elements of the form element, and so they are accessible as the childNodes of the form (X) The childNodes property returns
an array, which is then looped through Each time through the loop, the JavaScript checks the next element in the array to see if it is an input element Notice that both the strings INPUT and input are checked This is because some
Trang 8browsers capitalize element names and other browsers don’t For each input
element found, Z attaches the doAlert() function to the element’s onclick
anevent object that contains information about the event that caused the
doAlert() function to be called If that parameter is not filled in, it means the user is most likely using Internet Explorer In this case, \ is true The evt
variable is set to the Internet Explorer variable event, and thisBox is set to the checkbox that was clicked using Internet Explorer’s srcElement property If Firefox, or some other browser was used instead, the function’s evt parameter would already contain the event object, and we’d only need to set thisBox to the checkbox that was clicked by accessing the target property (])
One final note about assigning functions to event handlers using JavaScript: If for some reason you want to remove an event handler from
an object, simply set the handler’s value to null Here’s an example:
document.getElementById("myDiv").onclick = null;
Drop-Down Menus
I’ll close this chapter by showing how to build a basic drop-down menu with DHTML The menu shown in Figure 13-22 has three links: Dogs, Cats, and Birds Mousing over Cats
<html><head><title>Drop-Down Menus</title>
<script type = "text/javascript">
<! hide me from older browsers
X var div_array = new Array("divOne", "divTwo", "divThree");
function changeDiv(the_div, the_change)
{
Y document.getElementById(the_div).style.visibility = the_change;
causes a submenu to drop down with
the names of several cat breeds
Click-ing one of those links sends the browser
to a web page about that kind of cat
Figure 13-23 shows the code that drives this drop-down menu I’ve
already covered everything you must
know to understand this code, so take
a look at it, and see if you can figure
out how it works before reading my
Trang 9} function closeAll() {
Z for (var loop = 0; loop < div_array.length; loop++)
{ changeDiv(div_array[loop], "hidden");
} } // show me >
] <div id = "divOne" style =
"position:absolute; top:40; left:0; visibility:hidden;">
<a href = "#">Collie</a><br>
<a href = "#">Puli</a><br>
<a href = "#">Corgie</a><br>
</div>
<div id = "divTwo" style =
"position:absolute; top:40; left:80; visibility:hidden">
<a href = "#">Siamese</a><br>
<a href = "#">Manx</a><br>
<a href = "#">Calico</a><br>
</div>
<div id = "divThree" style =
"position:absolute; top:60; left:80; visibility:hidden">
<a href = "#">Parakeet</a><br>
<a href = "#">Finch</a><br>
<a href = "#">Canary</a><br>
Trang 10Line-by-Line Analysis of Figure 13-23
A drop-down menu has a div for each menu option The nine divs in Figure 13-23 include one div for each top-level menu element ([), one for each submenu (]), one for the bottom border, and one for the right border Each time a visitor mouses over one of the main menu options, only the sub-menu matching the link most recently moused over is shown If the visitor mouses over Cats, making the list of cat breeds visible, and then mouses over Dogs, the closeAll() function hides the Cats submenu and changeDiv()
displays the Dogs submenu Mousing over the bottom or right border closes all the submenus
The closeAll() Function
ThecloseAll() function loops through the array of divs defined in X Each time through the loop in Z,closeAll() calls the changeDiv() function to hide one of the divs
The changeDiv() Function
ThechangeDiv() function takes two parameters: the name of a div to change, and whether to make the div hidden or visible Line Y changes the visibility
of the specified div to visible or hidden, depending on the value of the ond parameter of changeDiv()
sec-The Borders
The menu’s bottom border is a long transparent (and therefore invisible) GIF (\) The code in \ dictates that mousing over this invisible GIF hides all submenus This GIF and the blank GIFs on the right of the menus make sure the submenu vanishes if the visitor’s mouse leaves the menu area completely
Figure 13-23 offers a basic example of how you might implement a archical menu For more complete versions, check out the menu and naviga-
hier-tion sechier-tion of Dynamic Drive’s website Fortune magazine’s website used this
one: http://www.dynamicdrive.com/dynamicindex1/dropmenuindex.htm
Summary
DHTML is the topic of several excellent books—what we’ve discussed here should just whet your appetite But you have learned a few DHTML basics, including the following:
z How to use divs to create blocks of HTML
z How to add styles to divs
z How to make divs, along with the HTML they contain, visible or invisible
z How to move divs
Trang 11z How to animate divs with timed loops
z How to use DOM methods to alter HTML documents
z How to read keyboard and mouse events
z How to create a basic hierarchical menu
If you understood all that, you shouldn’t have any problem with the assignment
Assignment
Create a DHTML screensaver like the one shown in Figure 13-24 The smiley face in the figure continually bounces around the screen When it hits one of the walls, it bounces off at a random angle To make the smiley face move diagonally, change its top and left positions in a timing loop To get it to bounce off a wall, make it change directions when it hits one side of the screen Remember, to make the smiley move right, you would add to its left
property, and to make it move left, you would subtract from its left property
Figure 13-24: A screensaver created with JavaScript
Trang 12A J A X B A S I C S
Ajax (Asynchronous JavaScript and XML) helps create web pages that act like desktop applications By combining DHTML with the ability to download and display information from
a webserver while a user is still interacting with a web page, Ajax puts an end to the old submit-and-wait cycle common to most interactive websites.
If you’ve used Google Maps (http://maps.google.com), you’ve seen Ajax
in action There are also Ajax versions of word processors, spreadsheets, and other common applications Like DHTML, Ajax is a complex topic and is the focus of a number of books However, with the JavaScript you’ve learned so far, and a few other details, you will be well on your way to becoming a master
of Ajax
This chapter introduces Ajax, including:
z An overview of Ajax and the technologies it encompasses
z The A in Ajax—Asynchronicity—and why you need it
z The basic JavaScript you’ll need for Ajax
Trang 13z Browser compatibility issues
z Potential pitfalls when using Ajax
z When to use Ajax and when to avoid it
z How to set up a webserver and write server-side programs that communicate with Ajax
This chapter tells only part of the Ajax story In Chapter 15 you’ll learn
about the X in Ajax (which stands for the data transfer standard XML), and
how to read and navigate XML documents in JavaScript and use them in Ajax applications
A Real-World Example of Ajax
The best-known example of Ajax may be Google Maps (maps.google.com) Figure 14-1 shows you the map which results from searching for the office of
No Starch Press The map is very interactive; you can zoom in, zoom out, and pan around without having to reload the page A smaller map in the bottom-right corner of the main map shows you the larger context of the map you’re viewing A blue box in the smaller map moves around as you pan across the large map
Figure 14-1: Google Maps
The map’s interface can mark places you ask about, such as No Starch Press in Figure 14-1, and show directions between two points For example, Figure 14-2 shows the route between the office and El Metate, one of my favorite Mexican restaurants in San Francisco All of this interactivity involves frequent trips to Google’s webservers without the user seeing the page reload
Trang 142 While the webserver is processing the requests, the web browser goes about its business as usual, allowing the user to continue interacting with the web page.
3 The result from each request appears once the webserver has processed that request, and it is used to update the web page using the DHTML techniques you learned in Chapter 13
Figure 14-3 shows how Ajax works and how it differs from the traditional style of communication between web browsers and webservers
In the traditional style of browser-server communication, a user clicks
a link or submits a form in a web browser This causes the browser to send a request for information to a webserver: either the web page named in the
href attribute of the link, or the results of a program or script named in the
action attribute of the <form> tag Once the request is sent, the browser sits idly, usually animating an icon in the upper-right corner of the window, and the user waits for the webserver to respond to the request Eventually the server responds, and the web page reloads, presenting new information
1 For Garrett’s original essay on Ajax, see http://adaptivepath.com/publications/essays/ archives/000385.php.
Trang 15Figure 14-3: Ajax versus traditional communications between a web browser and a webserver
In the Ajax style, on the other hand, the browser makes a request from the webserver without the user knowing about the request The icon in the browser’s corner doesn’t spin, and the browser can still be used When the response comes back from the webserver, the information displayed
in the web browser is updated without reloading the page The entire process occurs without causing a pause in the user’s interactions with the web page
the traditional style of browser-server communication described in the Before
Ajax part of Figure 14-3 is synchronous; that is, the browser submits a request
to a webserver and then waits for a reply, unable to send any other requests until the server responds
Before Ajax After Ajax
User submits form to webserver Moving off a text field sends
the server a secret message.
User waits while webserver thinks.
( ) ( )
The server thinks Meanwhile, the user keeps playing with the page.
Browser page reloads; user can continue Page is updated, but doesn’t reload.
User has not stopped enjoying the page.
Server done; sends answer back.
!
Server done; sends answer back.
User is still uninterrupted.
!
Trang 16An example of asynchronicity can be seen when you download a web page and watch images appearing on the page at different times The images are requested simultaneously, and the browser displays them as it receives them While this sort of asynchronicity is built in to all but the oldest web browsers, until recently JavaScript programmers couldn’t control asynch-ronous communications with webservers This all changed with the addition
of a new JavaScript object called the request object
XML—The X in Ajax
The X in Ajax stands for XML Since the publication of the XML standard in
1998, XML has become the format for sharing structured text-based
infor-mation between computers As we will see, browsers have built-in ways for dealing with information that has been formatted as XML documents This, and the ubiquity of XML documents, makes XML a great format for sharing information between web browsers and webservers
JavaScript—The J in Ajax
Ajax uses JavaScript to create requests, send them to webservers, parse the XML results, and update web pages accordingly The rest of the chapter describes how to use JavaScript to create and send requests, and deal with the asynchronous nature of the requests
Creating and Sending Requests
The key to implementing the Ajax-style communication described above is the
JavaScript request object, which is built into Internet Explorer 6.0 and later,
Firefox 0.8 and later, Opera 7.54 and later, and Safari 1.2.2 and later Your JavaScript can use this request object to query a webserver for information, store the returned information, and update the page when the server has provided the information
There are four steps involved in using JavaScript to make an Ajax request:
1 Creating a request object
2 Telling the request object where to send the request
3 Telling the object what to do when the request is answered
4 Telling the object to make the request
Creating a Request Object
The first step in making an Ajax request is to create a request object Sadly, there is a little bit of browser incompatibility involved in creating this object
In Internet Explorer,2 a request object is created like this:
var request = new ActiveXObject("Microsoft.XMLHTTP");
2 It’s possible to get slightly different versions of the request object from different versions of IE You only need to do this for fancy Ajax tricks that are beyond the scope of this discussion.
Trang 17In browsers other than Internet Explorer, do this:
var request = new XMLHttpRequest();
Putting these together gives this:
var request = null;
if (window.XMLHttpRequest) { request = new XMLHttpRequest();
} else if (window.ActiveXObject) { request = new ActiveXObject("Microsoft.XMLHTTP");
}
Once this block of JavaScript has executed, the request variable will contain
a request object
Telling the Object Where to Send the Request
The request object will request information from some resource Usually, that resource will be the webserver that served up the web page containing the JavaScript making the request In this case, the request object needs to know the URL of a program or script that lives on the webserver (known as
a server-side program) This server-side program will process the request and
respond with the requested information (Chapter 16 will focus more on server-side Ajax.)
If you don’t have access to a webserver, you can instead ask the request object to request a file that lives in the same directory as the file containing the JavaScript making the call To request a file, the request object simply needs to know the file’s name, such as my_file.txt Here’s how to tell a request object to request the file named my_file.txt:
request.open("GET", "my_file.txt");
Theopen method of the request object takes two parameters The first parameter is the type of request you want to make (GET,POST,HEAD, and so on) I’ll discuss the difference between these in Chapter 16; for now, we’ll only use GET
The second parameter is a string that tells the object where to send the request If the resource is password protected, the username and password can be provided as two additional (optional) parameters, like so:
request.open("GET", "my_file.txt", username, password);
What to Do When the Request Is Answered
As described in the introduction, a key feature of Ajax is asynchronicity After
a request object makes a request, the web browser is free to do whatever it wants, which may involve creating more request objects to make additional requests Each request object is responsible for tracking the process of making
Trang 18its request, waiting for a reply, and realizing when all the information provided
in response to the request has been completely downloaded Your task as a JavaScript coder is to tell each request object what it should do when the requested resource has been completely downloaded, using a special prop-erty of the request object called its readyState
As the request object moves through its stages, from creation, to being told about where to send the request, to sending the request, and so on, the value of the readyState property changes The property is called readyState
because each stage of a request object is called its state Table 14-1 lists the
values the readyState property can take and what they mean
The main trick in Ajax is to write a special function that is called whenever thereadyState property changes value To define this function and make sure it is called when the request object’s readyState property changes, do something like this:
We’ve seen plenty of event handlers before: onClick,onMouseOver, and
so on These handlers are part of the objects For example, a form button (<input type = "button">) will have an onClick handler, which is triggered whenever a user clicks the button We’ve used these handlers by referring
to them inside the HTML tag For example, the tag <input type = "button" onClick = "myFunction();"> will attach the function myFunction() to the button’sonClick event handler
Just as a button has an onClick handler, the request object has a handler called onreadystatechange, which is called automatically whenever the value of the request object’s readyState property changes And, just as we can attach a function to the button’s onClick handler, we can attach a function to the
onreadystatechange handler
Table 14-1: Values of a Request Object’s readyState Property
Property Value State Name Description
0 Uninitialized The object has been created but not told about the request:
open() has not been called.
1 Loading The object knows about the request but has not sent it yet:
send() has not been called.
2 Loaded The request has been sent, and basic information about
the response is available.
3 Interactive The response is being loaded into the request object.
4 Completed The entire response has been loaded into the request
object and is now available.
Trang 19However, in contrast to the button’s handler, we don’t stick the function into an HTML tag Instead, we set the onreadystatechange handler equal to
something called an anonymous function This function has no name; it is
simply called function By setting this handler equal to this anonymous function we ensure that whenever the request object’s readyState property changes, the function—that is, the code in the braces—is called It looks weird, but you’ll get used to it
Writing JavaScript That Is Called After the Request Has Been Answered
A request object begins life with a readyState of 0 Calling request.open()
tells the request object where to send the request, and switches the object’s
readyState to 1 Because the readyState has changed, the anonymous function attached to the onreadystatechange handler is called
Usually, you don’t want your JavaScript to do anything special at this point, so the function should not do anything when the readyState has been changed to 1 In fact, the function usually does not do anything until the
readyState has changed to 4, which, as you can see in Table 14-1, means that the request has been answered and that all the information sent by the server has been downloaded into the object Once readyState 4 is reached, the function is ready to do something with the data
Because JavaScripts usually don’t do anything until the request object reaches a readyState of 4, the anonymous function often looks something like this:
request.onreadystatechange = function() {
if (request.readyState == 4) { alert("Download complete! ");
} }
In the code above, the alert is called only after the request’s readyState
property changes to 4 The anonymous function is actually called when the property changes from 0 to 1, 1 to 2, and 2 to 3, but because of the if-then
statement, the alert is called only when the readyState changes to 4 Although this code sample calls an alert, more typically the JavaScript inside the if-then
statement will do something with the information that has been downloaded into the request object We’ll see examples of this soon
Sending the Request
Once you’ve told the request object where to send the request and what to
do when the request has been answered, it’s time to tell the request object to send the request, like so:
request.send(null);
Trang 20This command sends the request using the request object’s send method The single parameter of the send method contains information (for example, form information) to send to a webserver when making a POST request Because the request we’re making is of type GET (remember the first param-eter of the request.open() method), the parameter of the send method is set
tonull, which is a predefined term meaning “no information.”
Putting Everything Together
Figure 14-4 combines everything covered so far in one function, which includes creating the request object, telling it where to send the request, providing the anonymous function that is to be triggered when the request object changes state, and sending the request
<html><head><title>A Simple Ajax Script</title>
<script type = "text/javascript">
<! hide me from older browsers
` <input type = "button" value = "Make Ajax Request"
onClick = "doAjaxCall('sample.txt'); return true;">
Trang 21The action begins when the user clicks the button in `, which calls the
doAjaxCall() function (X) and sends it the name of a file to read
NOTE In general, a URL would go in here, but because I’m not assuming you have access to
a webserver, we’re just going to read a file that lives in the same directory as the file containing this JavaScript.
ThedoAjaxCall() function creates a new request object (Y), which is either an XMLHttpRequest object or an ActiveXObject object If the browser reading the JavaScript knows what the XMLHttpRequest object is, it will create
a new object of this type; if instead it knows what the ActiveXObject is, it will create a new object of this type If the browser doesn’t know either of these objects, request will stay equal to null
InZ, we make sure that a request object was created If not, _ lets the user know that he or she needs a browser upgrade
If a request object was created, [ tells it where to send the request The function to call when the readyState property of the request object changes is declared in \ This function says, “If the request is in state 4, the request object
has sent the request and received an answer; put the All done! message into the
div with the id of resultDiv (]).”
Finally, the request object makes the request in ^, which begins the process of downloading the requested text file The request object then goes through its five states, and each state change triggers the anonymous function
Once the request object is in state 4, the anonymous function writes All done!
into the div.The magic in all of this is that while the request object is performing the query and getting the results, the browser does not freeze up and the page does not reload And that is the beauty of Ajax
Getting the Results
The code in Figure 14-4 performs the request, retrieves the results, and puts
All done! into the div; it doesn’t actually display the retrieved results It’s as if
I asked you what you wanted for dinner and ignored what you said
Usually, once the request object has entered state 4, you will want to look
at the information the object has retrieved This information is stored in one
or two properties of the request object: The responseText property of the object always contains a text string with the results, and if the response is an XML document, the responseXML property of the request contains an XML object representing the results (more on this in Chapters 15 and 16) If the response
is not an XML document, responseXML will contain the value null
To put the results of the query into the div in a in Figure 14-4, change the body of the if-then statement in ] to
document.getElementById("resultDiv").innerHTML = request.responseText;