Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Tài liệu Scriptin’ with JavaScript and Ajax: A Designer’s Guide doc
Nội dung xem thử
Mô tả chi tiết
ptg
ptg
Scriptin’ with JavaScript
and Ajax:
A Designer’s Guide
CHARLES WYKE-SMITH
ptg
Scriptin’ with JavaScript and Ajax: A Designer’s Guide
Charles Wyke-Smith
New Riders
1249 Eighth Street
Berkeley, CA 94710
510/524-2178
Find us on the Web at www.newriders.com
To report errors, please send a note to [email protected]
New Riders is an imprint of Peachpit, a division of Pearson Education
Copyright © 2010 Charles Wyke-Smith
Development Editor and Compositor: Beth Bast
Project Editor: Nancy Peterson
Technical Editor: Christian Heilmann
Production Coordinator: Hilal Sala
Copy Editor and Proofreader: Anne Marie Walker
Marketing Manager: Glenn Bisignani
Indexer: Joy Dean Lee
Cover Design: Aren Howell
Cover Production: Hilal Sala
Interior Design: Mimi Heft
Notice of Rights
All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic,
mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contact [email protected].
Notice of Liability
The information in this book is distributed on an “As Is” basis without warranty. While every precaution has been
taken in the preparation of the book, neither the author nor Peachpit shall have any liability to any person or entity
with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained
in this book or by the computer software and hardware products described in it.
Trademarks
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designations
appear as requested by the owner of the trademark. All other product names and services identified throughout this
book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of
the trademark. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation
with this book.
Technical Note: This book was produced using Adobe InDesign. Code was developed in Adobe Dreamweaver.
Graphics were designed in Adobe Fireworks and Adobe Photoshop. Screenshots were taken with SnapzProX by
Ambrosia Software.
ISBN 13: 978-0-321-57260-8
ISBN 10: 0-321-57260-2
9 8 7 6 5 4 3 2 1
Printed and bound in the United States of America
ptg
For Beth
ptg
iv SCRIPTIN’ WITH JAVASCRIPT AND AJAX
Acknowledgments
I want to first thank Nancy Ruenzell, Peachpit’s publisher, for the
opportunity to write another book on the New Rider’s imprint, and
Michael Nolan, Peachpit Acquisitions Editor, for encouraging me to
complete the …in’ trilogy.
Nancy Peterson, my Project Editor, has been a wise and gracious
advisor while keeping me focused on the time deadline, which I
have actually met. Our weekly conference calls have been a wonderful source of guidance and encouragement, and have greatly
contributed to this book’s direction and focus. To you, Nancy, my
sincere thanks, and I hope we will meet in person sometime soon.
Thanks go to the editorial and production team at Peachpit: to
production editor Hilal Sala for her attention to the myriad details
getting the pages ready to go to press, to Anne Marie Walker for her
copyediting and proofing, and to Joy Dean Lee for the indexing.
Several programmers have worked with me on this book. Michael
Rosier assisted with the initial table of contents and some early code
examples. Mark Turansky has been a valuable source of advice and
ideas, and developed the framework examples in Chapter 6. Austin
Markus of Ithus in San Francisco, who was the technical editor on
my book Codin’ for the Web, wrote the PHP and much of the jQuery
for the Author Carousel example in Chapter 7.
My sincere thanks go to Chris Heilmann, International
Development Evangelist for the Yahoo! Development Network and
JavaScript genius. He has been invaluable as the technical editor
of this book, and I am grateful to him for his detailed and always
humorous feedback on the code. He also developed the YUI example in Chapter 7. I am glad that he is such a night owl because I have
often been able to videoconference with him on Skype in the early
hours in London where he lives to get advice when working late
here in South Carolina. It has been a great experience working with
Chris, and I thank him for the time he has given to this project.
Special thanks goes to Scott Fegette, Technical Product Manager
for Dreamweaver at Adobe, for his ongoing support and
encouragement.
A quick shout-out goes to David Sarnoff, Sean Rose, and
Mike Harding, fellow musicians in my band Mental Note (www.
mentalnoteband.com). Guys, being able to get out and play from
ptg
v
time to time during the development of this book has helped keep
me sane, and I appreciate your friendship and the time we spend
making music.
Once again, a big hug and a kiss for my wife Beth, who has
expanded her role from my previous books to Development Editor
on this one, and who has advised me on every aspect of it. She has
edited the drafts of the chapters, corrected my grammar, reedited
my run-on sentences (yes, still doing that), and had me rework my
explanations until I produced something she could understand. She
has coordinated the deliveries of the numerous rounds of chapters
with the Peachpit team, developed the diagrams from my sketches,
and, not least, laid out the entire book in its final form in Adobe
InDesign. Thanks to you, sweetie, we did it again!
To my lovely daughters, Jemma and Lucy, we once again have had
less time together while I have been writing, and now it’s time for
our vacation. I love you so much, appreciate your patience while I
have been shut in my office writing, and look forward to enjoying
the rest of the summer with you both.
Finally, I want to thank you, my readers, for buying my books and
for sharing your experiences using the techniques and ideas in
them. I’m delighted to have finally completed this JavaScript book in
response to all of you who have encouraged me to write it.
—Charles Wyke-Smith
Charleston, South Carolina, July 12, 2009
ACKNOWLEDGMENTS
ptg
vi SCRIPTIN’ WITH JAVASCRIPT AND AJAX
About the Author
Charles Wyke-Smith is the author of Stylin’ with CSS: A Designer’s
Guide and Codin’ for the Web: A Designer’s Guide to Developing
Dynamic Web Sites. Charles has been involved in print, multimedia and Web design for over twenty years. He founded PRINTZ
Electronic Design in San Francisco in the mid-eighties, an early allcomputerized design studio, and was a pioneer in interactive media
development.
He has been creating Web sites since 1994 and has provided Web
design and consulting service to companies including Wells-Fargo,
Benefitfocus, ESPN Video Games, and University of California, San
Francisco.
His work today focuses on online application development, with
an emphasis on user experience, information architecture, and
interface design.
An accomplished speaker and instructor, Charles has taught classes
in multimedia interface design and has presented at many industry
conference.
He lives with his wife, Beth, and two daughters in Charleston,
South Carolina.
ptg
vii
Contributors
Christian Heilmann is a geek and hacker by heart. He’s been a professional Web developer for about eleven years and worked his way
through several agencies up to Yahoo!, where he delivered Yahoo!
Maps Europe and Yahoo! Answers.
He’s written two books and contributed to three others on
JavaScript, Web development, and accessibility. He managed teams
in the U.S., India, and the U.K. to release dozens of online articles
and hundreds of blog posts in the last few years.
He’s been nominated Standards Champion of the Year 2008 by .net
magazine in the UK. Currently he sports the job title International
Developer Evangelist, spending his time going from conference to
conference and university to university to train people on systems
provided by Yahoo! and other Web companies.
Austin Markus is a Web application developer and principal of
Ithus Digital in San Francisco.
He first got excited about computers and programming in the preInternet days, running a BBS out of his bedroom and marveling
when people connected from around the country and the world.
His early work included developing ActionScript demonstration
applications for Macromedia and a Telex-to-Internet publishing
system for the San Francisco Chronicle.
Today, he develops applications from e-commerce stores, to content
management systems, to social networking applications.
Austin is a big believer in Open Source and has contributed modules
to Drupal and jQuery among others. He thinks the next big thing
will be pervasive computing and augmented reality. To this end,
he is presently working on an application for the Android mobile
platform to bridge the gap between the online and real world.
ABOUT THE AUTHOR & CONTRIBUTORS
ptg
viii SCRIPTIN’ WITH JAVASCRIPT AND AJAX
Contents
Introduction • xii
CHAPTER 1 : JAVASCRIPT COMES OF AGE • 2
Accessibility and Progressive Enhancement • 5
Three Steps to Progressive Enhancement • 7
1. Make It Functional • 8
2. Make It Look Good • 17
3. Enhance the Experience with JavaScript and Ajax • 21
Summary • 23
CHAPTER 2 : JAVASCRIPT BASICS • 24
Running the Code Examples • 26
Hello, JavaScript • 27
Scripts, Statements, and Comments • 28
Scripts • 28
Statements • 28
Comments • 29
Data and Ways to Store It • 30
Variables • 30
Strings • 32
Numbers • 34
Booleans • 34
Arrays • 34
Code that Acts on Data • 38
Operators • 38
Loops and Iterating Over Data • 46
Functions • 50
Summary • 55
CHAPTER 3 : OBJECTS AND THE DOM • 56
Objects • 58
Predefined JavaScript Objects • 59
ptg
ix
User-created Objects • 60
Objects and Instances • 63
DOMinating the Document • 68
Getting Around the DOM • 68
Get, Set...DOM! • 70
Modifying Element Styles • 75
Zebra Tables • 78
Refactoring the Code • 85
Summary • 87
CHAPTER 4 : EVENTS • 88
Techniques to Handle Events • 90
JavaScript Pseudo Protocol • 90
Inline Event Handler • 91
Handler as Object Property • 93
Event Listeners • 94
The First Event: load • 97
Adding Event Listeners on Page Load • 99
The Event Object • 103
The Event Object’s Type Property • 104
The Event Object in Microsoft Browsers • 105
The Secret Life of Events • 111
Capturing and Bubbling • 112
Event Delegation • 112
Striped Table with Rollovers • 113
Using an Element as a Debugging Tool • 113
Mouse Events • 114
Event Delegation • 114
Determining the Target Element • 116
Traversing the DOM • 118
Adding the Highlight • 120
The Up and Down Life of Keys • 122
Text Fields with Character Limits • 123
Setting Up the Message Display • 124
Monitoring the Character Count • 127
CONTENTS
ptg
x SCRIPTIN’ WITH JAVASCRIPT AND AJAX
The Finished Code • 130
Summary • 131
CHAPTER 5 : AJAX • 132
Understanding Ajax • 134
Ajax by the Letters • 134
Communication with the Server • 136
The XMLHttpRequest Object • 138
How to Use the XMLHttpRequest (XHR) Object • 139
Using the Ajax Function • 144
Using an Object Literal to Maintain State Through an Ajax
Call • 146
Ajax and Data Formats • 149
Creating a Simple Catalog • 149
Using PHP Templates • 150
An Ajax-ready Page • 155
Adding Ajax Functionality to the Catalog • 156
An Accessible Catalog • 161
Working with JSON • 162
The Guitar Catalog Using JSON • 164
Using XML • 167
Using Sajax—the Simple Ajax Framework • 173
Summary • 177
C HAP TE R 6 : FR A M E W O R K S • 178
About Frameworks • 180
Advantages of Frameworks • 180
Considerations When Using a Framework • 181
Namespacing • 182
Pseudo-global Variables • 184
Ajax Implementation in Four Frameworks • 186
jQuery Namespace • 186
Prototype • 188
Yahoo! User Interface (YUI) • 189
Adobe Spry • 190
ptg
xi
RIA Components • 191
Accordion with jQuery and Spry • 191
Highlight with Prototype and Spry • 195
Drag-and-drop with Prototype and jQuery • 197
Tabs with jQuery and Spry • 200
Summary • 203
CHAPTER 7 : TWO SIMPLE WEB APPLICATIONS • 204
About the Projects • 206
An Image Carousel • 207
A Location Finder with AutoComplete • 208
Building the Author Carousel • 209
Styling the Carousel • 211
Managing the Scrollbar • 214
The PHP Backend • 215
Layering on the JavaScript • 222
Implementing the Carousel Interactions • 224
Implementing the Overlay • 228
Parsing the JSON with JavaScript • 230
AutoComplete and Maps with the Yahoo! API • 233
The Location Data • 234
The Project Template—index.php • 234
The Search Form Script—searchform.php • 239
Implementing Search Without JavaScript—
searchresults.php • 248
Summary • 250
APPENDIX A • 252
APPENDIX B • 258
APPENDIX C • 272
APPENDIX D • 276
INDEX • 282
CONTENTS
ptg
xii SCRIPTIN’ WITH JAVASCRIPT AND AJAX
Introduction
Scriptin’ with JavaScript and Ajax is the third in a series of books
aimed at introducing designers and programmers to the process
of developing browser-based interfaces. The first, Stylin’ with CSS,
focuses on the structure and styling of content, and the second,
Codin’ for the Web, focuses on the three-tier architecture of browser,
middleware, and database that are the core components of almost
every Web site.
The focus of this third book is JavaScript, and a JavaScript-based
programming technique called Ajax that dramatically improves
communication between the user’s browser and the Web server.
The goal of this book is to teach you how to use JavaScript and Ajax
to develop sophisticated and responsive user interfaces for today’s
Web sites and online applications. Ajax has given a new purpose
to JavaScript, and virtually all of today’s successful sites and online
applications use JavaScript and Ajax extensively.
About This Book
My objective in writing this book is to provide you with a solid
understanding of how JavaScript is written and the possibilities it
offers, and how to develop robust and compact code that runs reliably in all modern Web browsers. Through numerous examples that
build on each other, you will develop the understanding and skills
to use JavaScript to improve the user experience and performance
of the Web sites you develop. All the examples can be readily added
into your own pages, which is a great way to start using JavaScript.
Along the way, I’ll show you techniques, shortcuts, and pitfalls
learned from the development of many projects.
As with my other books, the focus is on developing practical, professional, and, hopefully, profitable skills.
While this is a book about JavaScript, it has, by necessity, a broader
scope. JavaScript cannot be used in isolation: Its purpose is to
enhance a Web page with behaviors. It acts on a page’s structure (the
HTML markup) and its presentation (the CSS styling) to provide
interactivity in what would otherwise be a static page. Through Ajax
interactions, JavaScript can also request content from the server
by communicating with the middleware that generates pages and
manages communication with the database.
ptg
xiii
This means that HTML, CSS, and server middleware (I use PHP
in this book) must all be considered when discussing JavaScript.
Therefore, don’t be surprised to find that many pages of this book
illustrate HTML, CSS, and PHP code: This code is the context within
which JavaScript operates. I provide detailed explanations of the
purpose of such code, but you will benefit most from this book
if you already have a good grounding in HTML, CSS, and PHP or
another middleware language such as .NET or Java.
Also, let me state what this book is not. First, it is not a comprehensive coverage of JavaScript. While I show plenty of real-world
examples using coding techniques that are far beyond the basics,
I don’t cover the most advanced topics such as prototypal inheritance and closures. However, after reading Scriptin’, such subjects
will certainly be more understandable to you, and throughout, I
provide many references to resources that can further grow your
skills. Second, I don’t provide details of every property and method
of every object in the JavaScript language. There are many excellent
reference books and online resources available that can provide you
with that information, and I mention many of them in this book.
About JavaScript
JavaScript is the only programming language that runs in the
browser, and you cannot build a modern Web application without
it. Today’s users expect forms to be validated as they fill them out,
on-demand content delivery without waiting for new pages, and a
general application-like look and feel to the interface. JavaScript is
the key to meeting these expectations.
The lines between Web sites and online applications are becoming blurred: Is Facebook a Web site or an online application? It’s
accessed over the Web but its interface and its ability to update data
without page refreshes give it characteristics of a desktop application. Certainly, I use the term Web site and online application rather
interchangeably in this book—it may be becoming a meaningless
distinction.
As part of its new role in powering interactive interfaces, JavaScript
has recently been getting the kind of attention from browser developers that CSS received some years ago in an effort to standardize
its implementation across all browsers. CSS is now much improved
in this regard, but JavaScript still has many differences in the
way it works across the various browsers. These differences are a
throwback to the days of the “browser wars” where Netscape and
INTRODUCTION
ptg
xiv SCRIPTIN’ WITH JAVASCRIPT AND AJAX
Microsoft spent the late 90s developing competing features in an
effort to differentiate their virtually identical products.
JAVASCRIPT’S W3C AND MICROSOFT IMPLEMENTATION MODELS
A legacy of the browser wars is two different implementations of
JavaScript. Microsoft browsers adhere to what I will refer to in this
book as the Microsoft model, and other browsers, most notably
Firefox, Safari, and Opera, follow a standard that I refer to in this
book as the World Wide Web Consortium (W3C) model.
The most significant differences between the W3C and Microsoft
models are in three crucial areas of JavaScript’s implementation: the
event object that records the location (which element) and the type
(mouse click, key press, etc.) of user actions; the XMLHttpRequest
object that manages Ajax requests; and the load event, which
enables a page to be initialized with JavaScript-driven behaviors as
soon as it arrives in the browser. In this book, I’ll illustrate ways your
code can detect whether the user’s browser implements the W3C or
Microsoft model and respond appropriately.
These browser differences, the often verbose nature of JavaScript
code, and the demand for more sophisticated interactions in the
user interface have driven the development of numerous JavaScript
frameworks to address these issues. Frameworks, or libraries as they
are often known, provide extensive prebuilt functionality for common tasks, sophisticated interface components, cross-browser compatibility, and, in many cases, virtually a new language that runs on
top of JavaScript. Frameworks can dramatically reduce development
time, and I’ll show examples of several frameworks and their capabilities in the later chapters.
ACCESSIBILITY
For your Web site to reach the widest possible audience on the widest range of devices, JavaScript should be used only to enhance
already functional Web pages. No site should entirely depend on
JavaScript for its operation: This is an issue of accessibility that I
discuss in Chapter 1. Unfortunately, many sites today are totally
dependent on JavaScript for their operation. Such sites are unusable
by those who cannot run JavaScript in their browsers, who are visually impaired and rely on screen readers, or who are physically incapable of the gestures that a JavaScript-driven site may require, such
as using the mouse to drag and drop an element.