Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 54 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
54
Dung lượng
762,69 KB
Nội dung
372 Chapter 18 Consider the code in Figure 18-6. function getName() { var first_name = prompt("What's your first name?",""); var last_name = prompt("What's your last name?",""); var the_name = first_name + " " + last_name; } function theGreeting() { X debugger; var the_name = getName(); if (the_name == "Dave Thau") { alert("Howdy, partner!"); } else { alert("Ahoy, polloi!"); } } Figure 18-6: Starting the debugger As before, we suspect that something funny is going on with getName(). In this case, rather than putting in an alert or using logging, we invoke the JavaScript debugger in X. This stops the JavaScript program and makes the JavaScript debugger window look like Figure 18-7. The debugger; line appeared within theGreeting(), so the Local Variables section of the debugger shows you what it knows about the function. Initially, it knows that there is one variable, the_name, and that it has no value (the value is void). Figure 18-7: After X has been executed Debugging JavaScript and Ajax 373 After I click the Step Into button a couple of times to get into getName(), then fill in some prompts, the debugger in Figure 18-8 shows that first_name and last_name are set correctly. Figure 18-8: Examining variables; first_name and last_name look correct I click the Step Into button a few more times until I’ve exited getName(), and I see in Figure 18-9 that for some reason the_name is still void. From this I can deduce that the value is not getting passed out of the getName() function. Figure 18-9: Examining variables; the_name looks incorrect 374 Chapter 18 In this simple example, the complexity of a full-blown debugger such as Venkman is unnecessary. However, with complicated functions, being able to step through the JavaScript one line at a time, and see the values of the varia- bles at every step, can cut down debugging time immensely. If you’d like to learn more about how to use Venkman, you can find an excellent tutorial at http://www.svendtofte.com/code/learning_venkman. The Venkman debugger is by far the easiest JavaScript debugger to use and is itself a reason to download Firefox. If you are trying to debug a problem that occurs only in Internet Explorer, you will need a debugger that works for Internet Explorer. The best option here is the Microsoft Script Editor, 1 which comes packaged with Microsoft Office. Debugging Ajax in Firefox 1.5 and 2.0 Debugging Ajax is much like debugging JavaScript. However, the client-server communication that goes on in debugging Ajax adds a bit of complexity. An extension for Firefox 1.5 and 2.0 called Greasemonkey, 2 combined with a script called the XMLHttpRequest Debugging Script, 3 can give you a window into how your web browser and a webserver are communicating. Once you have downloaded and installed Greasemonkey and the XMLHttpRequest Debugging script, you can monitor requests sent and received by Firefox request objects. The XmlHttpRequestDebugging script maintains a list of JavaScripts that might have request objects that need to be monitored. To add JavaScripts that run on your desktop computer to that list, choose ToolsManage User Scripts from the Firefox menu, and add http://localhost/* to the Included Pages list, as seen in Figure 18-10. Once you have done so, a div is added to any web page on this list that makes an Ajax-style request. For example, Figure 18-11 shows the debugging window after Odysseus has logged into the To Do list application from Chapter 17. The figure shows two Ajax calls. The first line of a call tells you the type of call it was, in this case a GET. The next line tells you where the request was sent. The third line lets you see what message was sent with the request when the request.send() method was invoked. In the case of a GET, the message is null. With POST, the message will be the string sent. On the third line is also an [edit&replay] button, which gives you a window like Figure 18-12. In this window you can change the message sent in the request and then resend the request to see what happens. The fourth line of the window in Figure 18-11 gives you the status of the webserver’s response. Clicking [export] opens a window with the complete response from the webserver (Figure 18-13). As you can gather, this tool is extremely useful for debugging client-server communications in Ajax. 1 A good tutorial is available at http://www.jonathanboutelle.com/mt/archives/2006/01/ howto_debug_jav.html. 2 See http://greasemonkey.mozdev.org. 3 See http://blog.monstuff.com/archives/images/XMLHttpRequestDebugging.v1.2.user.js. Debugging JavaScript and Ajax 375 Figure 18-10: Adding JavaScripts that run on your desktop machine to the list of scripts to monitor NOTE Only you (and other users who have added Greasemonkey and the XMLHttpRequest Debugging script and have added your web page to their watch list) will see the XmlHttpRequest debugging window. Don’t worry about anyone else being affected by it. Figure 18-11: XmlHttpRequest debugger showing client-server traffic 376 Chapter 18 Figure 18-12: Using the XmlHttpRequest debugger to examine and edit an Ajax message Other Debugging Resources Before closing this section on debugging, I should mention two other debugging tools. Firebug 4 is a relatively new and popular debugger for Firefox 1.5 that combines logging, a JavaScript debugger, and the ability to watch Ajax requests. Microsoft’s Visual Web Developer Express Edition 5 is a free website development environment that includes a JavaScript debugger and can also watch Ajax requests. Fixing Bugs Once you’ve found where your bugs are, you need to fix them—and you have multiple options for this, both good and bad. This section covers a few things you should do when getting rid of bugs. 4 See http://www.joehewitt.com/software/firebug. 5 See http://msdn.microsoft.com/vstudio/express/vwd. Debugging JavaScript and Ajax 377 Figure 18-13: A detailed look at the client-server communication Back Up Your Program Some bugs are really hard to get rid of. In fact, sometimes in the process of eradicating a little bug that’s driving you nuts, you end up destroying your entire program. This happens a lot, so saving a backup of your program before you start to debug is the best way to ensure that a bug doesn’t get the best of you. Fix One Bug at a Time If you have multiple bugs, fix one and test your fix before moving to the next bug. Fixing a lot of bugs at once increases the risk of adding even more bugs. Avoid Voodoo Coding Sometimes you know a bug exists, but you don’t really know why. Let’s say you have a variable called index and for some reason index is always 1 less than you think it should be. At this point you can do two things. You can sit there for a while and figure out why index is 1 less than it should be, or you 378 Chapter 18 can just shrug, add 1 to index before using it, and move on. The latter method is called voodoo programming. When you start thinking, “What the hell? Why is index 2 instead of 3 here? Well . . . I’ll just add 1 for now and fix it later,” you’re engaging in voodoo programming. Voodoo programming may work in the short term, but eventually it will doom you. It’s like sweeping dust under a rug. The problem resurfaces— either you get yet another weird error you can’t figure out, or the next poor soul cursed to look at your code will find it extremely hard to understand. Don’t practice voodoo coding. Look for Similar Bugs In some ways, the ability to cut and paste code is the worst thing that ever happened to programmers. Often you’ll write some JavaScript in one function, then cut and paste it into another function. If the first function had a problem, you have now created problems in two functions. I’m not saying you shouldn’t cut and paste code—but keep in mind that bugs have a way of multiplying, so if you find one bug, look for similar bugs elsewhere in your code. One bug that typically crops up several times in every JavaScript is misspelled variable names. If you misspell the_name as teh_name in one place, chances are you’ve done it someplace else too. Clear Your Head You’re sitting there staring at a bug, and you just can’t figure out what’s going on or how to fix it. Or maybe you can’t even find the bug in the first place. The best thing to do is walk away from your computer. Go read a book and take a stroll around the corner. Get a tasty beverage. Do something— anything—but don’t think about the program or the problem. This tech- nique is called incubation, and it works amazingly well. After you’ve had a little break and relaxed a bit, try finding the bug again. Often you’ll approach the problem in a new, more fruitful way. Incubation works because it breaks you out of a dysfunctional mindset. Ask for Help Sometimes you get stuck in your own contorted thought patterns, and you need someone who hasn’t thought about the problem to find the hole in your logic. In structured coding environments, programmers periodically review each other’s code. Code review not only helps iron out bugs but also results in better code. Don’t be afraid to show other people your JavaScripts. You’ll become a better JavaScripter. Debugging JavaScript and Ajax 379 Summary Programming is a skill that improves dramatically over time, and learning how to debug efficiently is one of the biggest components of that process. Whenever you program, you will need to debug. A completely bug-free pro- gram is almost never written in one draft. The best you can do is to try to minimize the bugs and to write your programs in a way that makes it easy to detect and fix the bugs that slip in. The tools and techniques covered in this chapter should help make your debugging experience as pleasant as possible. Congratulations! You now know everything you need to start a career as an official JavaScripter. All that remains is lots and lots of practice. View source on every page that catches your fancy, and check out the free JavaScript resources listed in Appendix B. If you’ve made it this far, you’ve learned a lot of JavaScript, but this book hasn’t by any means covered every detail of this huge subject—so leaf through Appendix C to get a feel for the other JavaScript functions and objects at your disposal. If you’re going to do a lot of JavaScripting, get a good JavaScript reference book, like David Flanagan’s JavaScript: The Definitive Guide (O’Reilly, 2006). But most importantly, experiment freely and push the boundaries of what you’ve learned here. Now go forth and code! ANSWERS TO ASSIGNMENTS Here are solutions to the assignments I’ve given at the end of each chapter. The scripts and images used in the solutions may be found on this book’s companion website (http://www .bookofjavascript.com). The JavaScript in this appendix contains comments where I think explanation is neces- sary. If your solution works and is not much longer than mine, you’ve done a good job. There is no assignment for Chapter 1, so we’ll start with Chapter 2. Chapter 2 The Chapter 2 assignment asks you to change Figure 2-12 so that seconds are displayed along with minutes and hours. Use the Date object’s getSeconds() method to get the number of seconds and the fixTime() function to fix the formatting of the seconds. [...]... // if (the_ zone == "newyork") { the_ hours = the_ hours - 4; } else if (the_ zone == "sanfran") { the_ hours = the_ hours - 7; } else if (the_ zone == "tokyo") { the_ hours = the_ hours + 9; } // now fix the hours if over 24 or under 0 // if (the_ hours < 0) { the_ hours = the_ hours + 24; } else if (the_ hours > 24) { the_ hours = the_ hours - 24; } // put zeros in front of minutes and seconds if necessary the_ minutes... false;">Draw the histogram 388 Appendix A Chapter 9 This assignment asks you to alter Figure 9- 11 so that mousing over the image stops the slide show, and mousing off the image starts it again The solution is very much like Figure 9- 11 The only addition is the link around the image that clears the time-out when it is moused over and restarts the slideshow when the mouse moves off of it... in the book, take yourself out to dinner The assignment was to add these critical features to the To Do list application described in the chapter: Allow new users to join the service Allow a user to permit another user to access his or her To Do list Only the HTML file containing the JavaScript needs to be changed here First, you needed to make a change to the HTML at the bottom of the page to add the. .. != 2) { alert("Sorry, there must be one // in a domain name"); return false; } // Now check to see if the URL is legal see the alerts in the // if-then statement to see what the if-then statement is checking // If any of the conditions are violated, the script calls up an // alert box explaining the error and then uses return to exit // the function without changing the URL in the bottom frame if ((first_split[0]... zeros if necessary the_ day = fixTime (the_ day); the_ minutes = fixTime (the_ minutes); the_ seconds = fixTime (the_ seconds); // create the string you want to print // var the_ whole_date = the_ month + "/" + the_ day + " "; var the_ whole_time = the_ hour + ":" + the_ minutes + ":" + the_ seconds; // This is the time fixer function don't worry about how this works either function fixTime(number) { if (number < 10)... the time zone to // convert the time to The parameter can be either newyork, sanfran or // tokyo // The function determines the time for that time zone and then sets the // value of a text field to that time function updateReadout (the_ zone) { // get the current UTC time // var now = new Date(); var the_ hours = now.getUTCHours(); var the_ minutes = now.getUTCMinutes(); var the_ seconds = now.getUTCSeconds();... stores the values to the chart After collecting these values from the user, getNumbers() then loops through the array, calling drawSquares() to draw each line of the chart A n s w e rs to A s s i gn me n ts 387 Chapter 8 Assignment of bars to draw // and the length of those... "text /javascript" > the date information // var today = new Date(); var the_ day = today.getDate(); var the_ month = today.getMonth(); var the_ hour = today.getHours(); var the_ minutes = today.getMinutes(); var the_ seconds = today.getSeconds(); // correct for the month starting from zero // the_ month = the_ month + 1; // add leading zeros if necessary the_ day = fixTime (the_ day);... Chapter 9 Assignment the images var the_ images = new Array(); the_ images[0] = new Image(); the_ images[0].src = "one.jpg"; the_ images[1] = new Image(); the_ images[1].src = "two.jpg"; the_ images[2] = new Image(); the_ images[2].src = "three.jpg"; var the_ timeout; var index = 0; // function rotateImage() swaps in the next... tells the time in San Francisco, New York, London, and Tokyo The clock should have a text field for the time, a button to update the clock, and four radio buttons, one for each of those time zones When you click on one of the radio buttons, A n s w e rs to A s s i gn me n ts 385 the correct time should appear in the text field When you click on the update button, the clock should update with the time . the_ hours = the_ hours - 4; } else if (the_ zone == "sanfran") { the_ hours = the_ hours - 7; } else if (the_ zone == "tokyo") { the_ hours = the_ hours + 9; } // now fix the. request and then resend the request to see what happens. The fourth line of the window in Figure 18-11 gives you the status of the webserver’s response. Clicking [export] opens a window with the complete. = fixTime (the_ day); the_ minutes = fixTime (the_ minutes); the_ seconds = fixTime (the_ seconds); // create the string you want to print // var the_ whole_date = the_ month + "/" + the_ day +