5 Comparing the user experiences 5 ■ Network latency 9 Asynchronous interactions 12 ■ Sovereign and transient usage patterns 15 ■ Unlearning the Web 16 1.2 The four defining principles o
Trang 1M A N N I N G
Dave Crane Eric Pascarello
with Darren James
Trang 2Ajax in Action
Trang 3Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 4Ajax in Action
DAVE CRANE ERIC PASCARELLO
WITH DARREN JAMES
M A N N I N GGreenwich (74° w long.)
Trang 5For online information and ordering of this and other Manning books, please go to www.manning.com The publisher offers discounts on this book when ordered in quantity For more information, please contact:
Special Sales Department
Manning Publications Co.
©2006 by Manning Publications Co All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy
to have the books they publish printed on acid-free paper, and we exert our best efforts
to that end.
Manning Publications Co Copyeditor: Liz Welch
209 Bruce Park Avenue Typesetter: Denis Dalinnik
Greenwich, CT 06830 Cover designer: Leslie Haimes
Trang 6To Hermes, Apollo, Athena, and my cats, for their wisdom
—D.C.
To my wife; I’m surprised you said yes —E.P.
To my red-headed wife —D.J.
Trang 7Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 8PART 1 RETHINKING THE WEB APPLICATION 1
PART 2 CORE TECHNIQUES 117
PART 3 PROFESSIONAL AJAX 209
brief contents
Trang 9viii BRIEF CONTENTS
PART 4 AJAX BY EXAMPLE 325
Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 10preface xix acknowledgments xxi about this book xxiv
PART 1 RETHINKING THE WEBAPPLICATION 1
1.1 Why Ajax rich clients? 5
Comparing the user experiences 5 ■ Network latency 9 Asynchronous interactions 12 ■ Sovereign and transient usage patterns 15 ■ Unlearning the Web 16
1.2 The four defining principles of Ajax 17
The browser hosts an application, not content 17 ■ The server delivers data, not content 19 ■ User interaction with the application can be fluid and continuous 21 ■ This is real coding and requires discipline 23
1.3 Ajax rich clients in the real world 24
Surveying the field 24 ■ Google Maps 25
1.4 Alternatives to Ajax 28
Macromedia Flash-based solutions 28 ■ Java Web Start and related technologies 28
contents
Trang 11x CONTENTS
1.5 Summary 29
1.6 Resources 30
2.1 The key elements of Ajax 32
2.2 Orchestrating the user experience with JavaScript 34
2.3 Defining look and feel using CSS 36
CSS selectors 37 ■ CSS style properties 39
A simple CSS example 40
2.4 Organizing the view using the DOM 45
Working with the DOM using JavaScript 47 ■ Finding a DOM node 49 ■ Creating a DOM node 50 ■ Adding styles to your document 51 ■ A shortcut: Using the innerHTML property 53
2.5 Loading data asynchronously using
XML technologies 53 IFrames 54 ■ XmlDocument and XMLHttpRequest objects 56 Sending a request to the server 58 ■ Using callback functions to monitor the request 61 ■ The full lifecycle 62
2.6 What sets Ajax apart 65
2.7 Summary 67
2.8 Resources 68
3.1 Order out of chaos 71
Patterns: Creating a common vocabulary 71 Refactoring and Ajax 72 ■ Keeping a sense of proportion 73 Refactoring in action 73
3.2 Some small refactoring case studies 77
Cross-browser inconsistencies: Façade and Adapter patterns 77 Managing event handlers: Observer pattern 80
Reusing user action handlers: Command pattern 83 Keeping only one reference to a resource: Singleton pattern 87
Trang 12CONTENTS xi
3.5 Third-party libraries and frameworks 103
Cross-browser libraries 104 ■ Widgets and widget suites 108 Application frameworks 111
3.6 Summary 114
3.7 Resources 115
PART 2 CORE TECHNIQUES 117
4.1 A different kind of MVC 120
Repeating the pattern at different scales 120 Applying MVC in the browser 122
4.2 The View in an Ajax application 124
Keeping the logic out of the View 124 Keeping the View out of the logic 130
4.3 The Controller in an Ajax application 134
Classic JavaScript event handlers 134 The W3C event model 137
Implementing a flexible event model in JavaScript 138
4.4 Models in an Ajax application 143
Using JavaScript to model the business domain 144 Interacting with the server 145
4.5 Generating the View from the Model 147
Reflecting on a JavaScript object 147 ■ Dealing with arrays and objects 151 ■ Adding a Controller 154
4.6 Summary 157
4.7 Resources 158
5.1 Working with the server side 160
5.2 Coding the server side 161
Popular implementation languages 161 N-tier architectures 162
Maintaining client-side and server-side domain models 163
Trang 13xii CONTENTS
5.3 The big picture: common server-side designs 164
Naive web server coding without a framework 164 Working with Model2 workflow frameworks 166 Working with component-based frameworks 167 Working with service-oriented architectures 170
5.4 The details: exchanging data 174
Client-only interactions 175 Introducing the planet browser example 175 Thinking like a web page: content-centric interactions 178 Thinking like a plug-in: script-centric interactions 182 Thinking like an application: data-centric interactions 188
5.5 Writing to the server 193
Using HTML forms 193 ■ Using the XMLHttpRequest object 195 ■ Managing user updates effectively 197
5.6 Summary 206
5.7 Resources 207
PART 3 PROFESSIONAL AJAX 209
6.1 Getting it right: building a quality application 212
Responsiveness 213 ■ Robustness 213 ■ Consistency 214 Simplicity 215 ■ Making it work 215
6.2 Keeping the user informed 216
Handling responses to our own requests 216 Handling updates from other users 218
6.3 Designing a notification system for Ajax 222
Modeling notifications 223 Defining user interface requirements 225
6.4 Implementing a notification framework 226
Rendering status bar icons 226 ■ Rendering detailed notifications 229 ■ Putting the pieces together 230
6.5 Using the framework with network requests 237
6.6 Indicating freshness of data 241
Defining a simple highlighting style 241 Highlighting with the Scriptaculous Effects library 243
Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 14CONTENTS xiii
6.7 Summary 244
6.8 Resources 245
7.1 JavaScript and browser security 247
Introducing the “server of origin” policy 248 ■ Considerations for Ajax 248 ■ Problems with subdomains 249
Cross-browser security 250
7.2 Communicating with remote services 251
Proxying remote services 252 Working with web services 253
7.3 Protecting confidential data 263
The man in the middle 263 ■ Using secure HTTP 264 Encrypting data over plain HTTP using JavaScript 266
7.4 Policing access to Ajax data streams 268
Designing a secure web tier 268 Restricting access to web data 272
7.5 Summary 277
7.6 Resources 278
8.1 What is performance? 280
8.2 JavaScript execution speed 281
Timing your application the hard way 282 Using the Venkman profiler 288
Optimizing execution speed for Ajax 289
8.3 JavaScript memory footprint 302
Avoiding memory leaks 302 Special considerations for Ajax 306
8.4 Designing for performance 311
Measuring memory footprint 312 ■ A simple example 316 Results: how to reduce memory footprint 150-fold 321
8.5 Summary 323
8.6 Resources 324
Trang 15xiv CONTENTS
PART 4 AJAX BY EXAMPLE 325
9.1 A double-combo script 328
Limitations of a client-side solution 328 Limitations of a server-side solution 329 Ajax-based solution 330
9.2 The client-side architecture 331
Designing the form 331 Designing the client/server interactions 333
9.3 Implementing the server: VB NET 334
Defining the XML response format 335 Writing the server-side code 336
9.4 Presenting the results 339
Navigating the XML document 339 Applying Cascading Style Sheets 342
10.1 Examining type-ahead frameworks 362
Type-ahead suggest frameworks 362 ■ Google Suggest 364 The Ajax in Action type-ahead 365
10.2 The server-side framework: C# 366
The server and the database 366 Testing the server-side code 368
10.3 The client-side framework 369
The HTML 369 ■ The JavaScript 370 Accessing the server 380
Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 16CONTENTS xv
10.4 Adding functionality: multiple elements
with different queries 392
10.5 Refactoring 392
Day 1: developing the TextSuggest component game plan 394 Day 2: TextSuggest creation—clean and configurable 397 Day 3: Ajax enabled 401 ■ Day 4: handling events 406 Day 5: the suggestions pop-up UI 413
Refactor debriefing 421
10.6 Summary 422
11.1 The evolving portal 424
The classic portal 424 ■ The rich user interface portal 426
11.2 The Ajax portal architecture using Java 427
11.3 The Ajax login 429
The user table 429 ■ The server-side login code: Java 430 The client-side login framework 433
11.4 Implementing DHTML windows 439
The portal windows database 439 The portal window’s server-side code 441 Adding the JS external library 445
11.5 Adding Ajax autosave functionality 448
Adapting the library 448 Autosaving the information to the database 450
12.1 Understanding the search techniques 467
Looking at the classic search 467 ■ The flaws of the frame and
pop-up methods 469 ■ Examining a live search with Ajax and XSLT 470 ■ Sending the results back to the client 472
Trang 17xvi CONTENTS
12.2 The client-side code 473
Setting up the client 473 Initiating the process 474
12.3 The server-side code: PHP 476
Building the XML document 476 Building the XSLT document 479
12.4 Combining the XSLT and XML documents 481
Working with Microsoft Internet Explorer 483 Working with Mozilla 484
12.5 Completing the search 485
Applying a Cascading Style Sheet 485 ■ Improving the search 487 ■ Deciding to use XSLT 489
Overcoming the Ajax bookmark pitfall 490
12.6 Refactoring 491
An XSLTHelper 492 ■ A live search component 496 Refactoring debriefing 501
12.7 Summary 501
13.1 Reading information from the outside world 504
Discovering XML feeds 505 Examining the RSS structure 506
13.2 Creating the rich user interface 509
The process 510 ■ The table-less HTML framework 511 Compliant CSS formatting 513
13.3 Loading the RSS feeds 518
Global scope 518 ■ Ajax preloading functionality 520
13.4 Adding a rich transition effect 524
Cross-browser opacity rules 524 ■ Implementing the fading transition 525 ■ Integrating JavaScript timers 527
Trang 18CONTENTS xvii
13.6 Avoiding the project’s restrictions 534
Overcoming Mozilla’s security restriction 534 Changing the application scope 537
13.7 Refactoring 537
RSS reader Model 537 ■ RSS reader view 541 RSS reader Controller 545 ■ Refactoring debrief 558
13.8 Summary 559
appendix A The Ajax craftsperson’s toolkit 561
A.1 Working smarter with the right toolset 562
A.2 Editors and IDEs 565
A.3 Debuggers 571
A.4 DOM inspectors 582
A.5 Installing Firefox extensions 585
A.6 Resources 588
appendix B JavaScript for object-oriented programmers 589
B.1 JavaScript is not Java 590
Trang 20preface
Sometimes your destiny will follow you around for years before you notice it Amidst the medley of fascinating new technologies that I was playing—I mean
working—with in the early 1990s was a stunted little scripting language called
JavaScript I soon realized that, despite its name, it didn’t really have anything
to do with my beloved Java, but it persistently dogged my every step
By the late 90s, I had decided to cut my hair and get a proper job, and found myself working with the early adopters of digital set-top box technol-ogy The user interface for this substantial piece of software was written entirely in JavaScript and I found myself the technical lead of a small team of developers writing window-management code, schedulers, and all kinds of clever stuff in this language “How curious,” I thought “It’ll never catch on.” With time I moved on to more demanding work, developing the enter-prise messaging backbone and various user interface components for an
“intelligent,” talking “House of the Future.” I was hired for my Java skills, but
I was soon writing fancy JavaScript user interfaces again It was astonishing to find that some people were now taking this scripting language seriously enough to write frameworks for it I quickly picked up the early versions of Mike Foster’s x library (which you’ll find put into occasional action in this book) One afternoon, while working on an email and text message bulletin board, I had the weird, exciting idea of checking for new messages in a hid-
den frame and adding them to the user interface without refreshing the screen
Trang 21Destiny was sniffing at my heels My next job landed me in a heavy-duty development role, building software for big Tier 1 banks We use a mixture of Java and JavaScript and employ tricks with hidden frames and other things My team currently looks after more than 1.5 million bytes of such code—that’s static JavaScript, in addition to code we generate from JSPs No, I’m not counting any image resources in there either We use it to develop applications for hundreds of operators managing millions of dollars’ worth of accounts Your bank account may well be managed by this software.
Somewhere along the way, JavaScript had grown up without my quite ing it In February 2005, Jesse James Garrett provided the missing piece of the jigsaw puzzle He gave a short, snappy name to the cross-browser-asynchronous-rich-client-dynamic-HTML-client-server technology that had been sneaking up
realiz-on us all for the last few years: Ajax.
And the rest, as they say, is history Ajax is generating a lot of interest now, and a lot of good code is getting written by the people behind Prototype, Rico, Dojo, qooxdoo, Sarissa, and numerous other frameworks, too plentiful to count Actually, we do try to count them, in appendix C We think we’ve rounded up
most of the suspects And I’ve never had so much fun playing—I mean working—
with computers
We have not arrived yet The field is still evolving I was amazed to see just how much when I did the final edits in September on the first chapter that I wrote back in May! There’s still a lot of thinking to be done on this subject, and the next year or two will be exciting I’ve been very lucky to have Eric and Darren
on the book piece of the journey with me so far
We hope you will join us—and enjoy the ride
DAVE CRANE
Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 22acknowledgments
Although there are only three names on the cover of this book, a legion of ented, hardworking, and just plain crazy people supported us behind the scenes We’d like to thank everyone at Manning, especially our publisher, Mar-jan Bace, and our development editors, Jackie Carter and Doug Bennett, for their continuous support and help on so many aspects of the manuscript To the others at Manning who worked with us in different stages of the project—Blaise Bace, review editor Karen Tegtmayer, webmaster Iain Shigeoka, publi-cist Helen Trimes, and not least of all project editor Mary Piergies—thanks for helping to steer us along so smoothly Our copyeditors, Linda Recktenwald and Liz Welch, and proofreaders Barbara Mirecki and Tiffany Taylor, proved
tal-to be indispensable, and design edital-tor Dottie Marsico and typesetter Denis Dalinnik did a marvelous job of converting our scribbles into pictures and our text into a real book!
Many talented coders gave their time unflinchingly to our cause, as cal proofreaders and reviewers Leading the charge were Phil McCarthy (who not only corrected our code, but also our grammar and style, even setting us straight on the rules of Battleship) and Bear Bibeault, who bravely advised on server architecture, client-side code, and Mac compatibility, in the face of Hur-ricane Rita Joe Mayo, Valentin Crettaz, James Tikalsky, Shane Witbeck, Frank Zammetti, Joel Webber, Jonathan Esterhazy, Garret Wilson, Joe Walker, and
Trang 23Thanks to Paul Hobbs, Bill Gathen, and Charlie Arehart for spotting typos in the code in the Manning Early Access Program chapters (MEAP) Finally, special thanks are due to Brian J Sletten, Ben Galbraith, and Kito Mann for helping to get the ball rolling in the first place Our thanks also go to the authors of the many Ajax frameworks that we have used in the book, and to Jesse James Garrett for providing us with a short, snappy acronym to grace the cover of our book (We feel that “Those Rich Client JavaScript Network Things in Action” wouldn’t have been quite as effective.)
We’re standing on the shoulders of a whole group of giants here The view is fantastic
DAVE CRANE
I’d like to thank Chia, Ben, and Sophie for their support, wisdom, and asm, and for putting up with me through all the late nights and early mornings I’m finished now and I promise to behave Thanks too to my parents for listen-ing to the book-writing saga unfold and for instilling in me the strength and foolishness to undertake such a project in the first place
Eric and Darren have been excellent co-authors to work with, and I’d like to extend my thanks to them too, for their invaluable contributions to the book
My thanks to my colleagues at Smartstream Technologies for exploring the world of Ajax with me before it was christened—Tony Coombes, John Kellett, Phil McCarthy, Anthony Warner, Jon Green, Rob Golder, David Higgins, Owen Rees-Hayward, Greg Nwosu, Hristo Gramatikov, and Stuart Martin, and to my manag-ers Colin Reid and Andrew Elmore Thanks too to our colleagues overseas: Bhu-pendra, Pooja, Rahul, Dhiraj, Josef, Vjeko and Ted, and to the many other talented people with whom I’ve had the pleasure to work over the years Special thanks are due to Rodrigo Barnes for introducing me to this new programming
Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 25about this book
Ajax is a growing new technology at the time of this writing and we’re delighted to bring you the lowdown on it, in the inimitable style of Manning’s
In Action series In doing so, though, we faced an interesting problem
Although Ajax is indisputably hot, it isn’t really new It isn’t really a ogy, either
Let us explain Ajax brings together several well-established web gies and uses them in new and interesting ways Learning to use a completely new technology for the first time is in some ways simpler because you start with a blank slate Ajax is different: there is also much to unlearn Because of
technolo-this, our book is organized somewhat differently from most Manning In Action
books You may notice this when reading and should know that we feel the way
it is organized best suits this subject
And, as you will see, although the Ajax technologies themselves are all ent side, the differences extend all the way down to the server This book is mainly about client-side programming, and most of the code examples that you’ll find in here are JavaScript The principles of Ajax decouple the client from the server beautifully, and can be used with any server-side language We’ve therefore got a broad audience to address and have opted to present our server-side code in a mixture of languages: PHP, Java, C#, and Visual Basic NET More importantly, though, we’ve tried to keep the server-side code relatively simple and implementation-agnostic, so that you can port it to what-
cli-Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 26ABOUT THIS BOOK xxv
ever environment you choose Where we do use language-specific features, we explain them in enough detail for those unfamiliar with that particular environ-ment to figure out what we’re doing
Who should read this book?
Ajax is at the crossroads of a number of disciplines; readers will approach it from
a number of directions On the one hand there are professional enterprise opers with computer science degrees and several years of hands-on experience with large software projects, who need to sometimes pop their heads above the battlements and work with the presentation tier On the other hand are creative professionals who have moved from graphic design to web design and “new media,” and taught themselves how to program using scripting languages such
devel-as PHP, Visual Basic, or JavaScript/ActionScript In between there are desktop app developers retraining for the Web and sysadmins called upon to put together web-based management tools, as well as many others
All of these possible readers have a real interest in Ajax We’ve tried to address the needs of all of them, at least to some extent, in this book We provide pointers to the basic web technologies for the server-side developer used to treating the web browser as a dumb terminal We also give a grounding in soft-ware design and organization for the new media developer who may be more used to ad hoc coding styles Wherever you come from, Ajax is a cross-disciplin-ary technology and will lead you into some unfamiliar areas We’re going to stretch you a bit, and ask you to pick up a few new skills along the way We’ve done the same in our own use of Ajax, even while writing this book We have found it to be a very rewarding and enjoyable experience, with benefits extend-ing to other aspects of our professional lives
Roadmap
This book is divided into four parts Part 1 will tell you what Ajax is, explain why
it is a useful addition to your development toolbox, and introduce the tools that can make you successful Part 2 covers the core techniques that make an Ajax application work, and part 3 builds on these to discuss what is needed to go from proof of concept to production-ready software In part 4 we take a direct hands-
on approach, and build five Ajax projects step by step; we then refactor them into drop-in components that you can use in your own web applications
Trang 27xxvi ABOUT THIS BOOK
As we have said, Ajax is not a technology but a process We’ve therefore cated chapter 1 to reorienting developers familiar with pre-Ajax web develop-ment We discuss the fundamental differences between Ajax and the classic web application, how to think about usability, and other conceptual goodies If you want to find out what the buzz around Ajax is, we suggest you start here If you just want to eat, drink, and sleep code, then you’d best move on to chapter 2 The Ajax technologies are all reasonably well documented in their own right already We’ve provided a whistle-stop, example-driven run through these tech-nologies in chapter 2, but we haven’t aimed at being comprehensive What we have done is emphasize where the technology is used differently, or behaves dif-ferently, as a result of being part of Ajax
Chapter 3 introduces the third main theme for this book, managing the Ajax codebase Having watched a JavaScript codebase grow to over 1.5 MB of source code, we can attest to the fact that writing JavaScript for Ajax is a different ball game We talk design patterns and refactoring here, not because we think they’re cool, but because we’ve found them to be invaluable, practical tools in working with Ajax And we think you will too as you start to pick up speed
In chapters 4 and 5, we turn our sights on the core components of Ajax, and apply our design pattern knowledge to find the best practices Chapter 4 looks at ways of keeping your code clean on the client itself, applying the old web work-horse, Model-View-Controller, in a new way Chapter 5 looks at the different ways
of communicating between the client and the server and how various types of frameworks can be adapted to work with Ajax By this point, we have covered all the basic plumbing and you’ll know how Ajax operates end to end
Chapters 6 through 8 build on the fundamental knowledge that we’ve acquired to look at how to add polish to your application and go beyond a proof
of concept to something that’s fun, and safe, to usable in the real world Chapter
6 addresses the user experience, and takes an in-depth look at ways of keeping the user informed while asynchronous tasks are executing There’s a balance to
be struck between keeping out of the user’s way and keeping him in the dark, and we show you how to find that happy middle ground here
Chapter 7 looks at the issue of security in Ajax from a number of angles Ajax
is a web technology and many of the issues that it faces are no different from any other web app We cover the basic ground, concentrating on Ajax-specific issues here, such as securely importing generated JavaScript from the server, and pro-tecting your web service entry points from unwanted direct manipulation Secu-rity can be a showstopper for serious applications, and we give the basic steps needed to keep it under control here
Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 28ABOUT THIS BOOK xxvii
Chapter 8 discusses that other showstopper, performance (or rather, lack of it!) We show how to monitor the performance of your application and how to analyze code in order to improve it and keep those improvements consistent across an application
In part 4, which consists of chapters 9 through 13, we switch gears to look at a number of Ajax projects In each case, we code the functionality up in a straight-forward way and then refactor it into something robust that you can drop into your own projects with no more than a few lines of code This gives you the bene-fit of understanding the principles, the benefits of reuse, as well as showing Ajax refactoring in action
In chapter 9, we look at a simple way to give the user a richer experience
by enhancing HTML forms with Ajax: we use data entered in one field to populate a second drop-down list by making a background request to the server We continue the theme of form enhancement in chapter 10 with an implementation of type-ahead suggest, fetching data from the server in response to user keystrokes
Chapter 11 moves on to the wider possibilities of Ajax user interfaces We develop a complete portal application that resembles a workstation desktop more than a web page, complete with its own draggable, resizable windows Ajax processes track window movements in the background, so that the desktop is always in the same state you left it, even if you log back in on a different machine Chapter 12 develops an Ajax-based search system and demonstrates the power of client-side XSLT as a way of turning raw XML data into formatted, styled content
In chapter 13, we present an Ajax client without a back-end implementation
It still talks to server processes, but in this case, does so directly to blog and news syndication feeds, using the Internet standard RSS protocol
Finally, we include three appendices that we hope you’ll find useful The body
of the book discusses the technology itself With a new, cross-disciplinary nology, assembling the tools to use it effectively is more of a challenge than with
tech-a mtech-ature technology sttech-ack such tech-as J2EE or NET The vendors haven’t started offering Ajax tools yet, but we’re sure that they will! In the meantime, we provide
in appendix A an overview of the tools and tricks that we’ve used to develop our Ajax projects and to keep our house in order
Appendix B is for enterprise programmers who understand software design principles but aren’t quite sure how to apply them in such a flexible, unstructured, and well, downright odd language as JavaScript We walk through what the lan-guage can do, and point out where the main divergences from Java and C# lie
Trang 29xxviii ABOUT THIS BOOK
If the tool vendors haven’t quite caught up with Ajax yet, neither have the framework developers The Ajax framework scene is a hotbed of innovation, intrigue (and often re-invention) right now Appendix C rounds up the Ajax frameworks and toolkits that we know of at the moment, and provides a short overview and link for each
Code conventions
All source code in listings or in text is in a fixed-widthfontlikethis to separate
it from ordinary text We make use of many languages and markups in this book—JavaScript, HTML, CSS, XML, Java, C#, Visual Basic NET, and PHP—but
we try to adopt a consistent approach Method and function names, object erties, XML elements, and attributes in text are presented using this same font
In many cases, the original source code has been reformatted: we’ve added line breaks and reworked indentation to accommodate the available page space
in the book In rare cases even this was not enough, and listings include tinuation markers Additionally, many comments have been removed from the listings Where appropriate, we’ve also cut implementation details that distract rather than help tell the story, such as JavaBean setters and getters, import and include statements, and namespace declarations
Code annotations accompany many of the listings, highlighting tant concepts In some cases, numbered bullets link to explanations that fol-low the listing
IIS These are in addition to the full working examples, so that if you do enjoy wrestling with databases and app servers, you can dig in Some basic setup docu-mentation is provided with the download
Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 30ABOUT THIS BOOK xxix
Author Online
Purchase of Ajax in Action includes free access to a private web forum run by
Man-ning Publications where you can make comments about the book, ask technical questions, and receive help from the authors and from other users To access the forum and subscribe to it, point your web browser to http://www.manning.com/crane This page provides information on how to get on the forum once you are registered, what kind of help is available, and the rules of conduct on the forum Manning’s commitment to our readers is to provide a venue where a mean-ingful dialogue between individual readers and between readers and the authors can take place It is not a commitment to any specific amount of participation on the part of the authors, whose contribution to the book’s forum remains volun-tary (and unpaid) We suggest you try asking the authors some challenging ques-tions, lest their interest stray!
The Author Online forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print
About the title
By combining introductions, overviews, and how-to examples, the In Action
books are designed to help learning and remembering According to research in cognitive science, the things people best remember are things they discover dur-ing self-motivated exploration
Although no one at Manning is a cognitive scientist, we are convinced that in order for learning to become permanent it must pass through stages of explora-tion, play, and, interestingly, retelling of what was learned People understand and remember new things, which is to say they master them, only after actively
exploring them Humans learn in action An essential part of all In Action guides
is that they are example-driven This encourages readers to try things out, to play with new code, and explore new ideas
There is another, more mundane, reason for the title of this book: our readers are busy They use books to do a job or to solve a problem They need books that allow them to jump in and jump out easily and learn just what they want just when they want it They need books that aid them “in action.” The books in this series are designed for such readers
Trang 31xxx ABOUT THIS BOOK
About the cover illustration
The figure on the cover of Ajax in Action is a “Sultana,” a female member of a
sul-tan’s family; both his wife and his mother could be addressed by that name The illustration is taken from a collection of costumes of the Ottoman Empire pub-lished on January 1, 1802, by William Miller of Old Bond Street, London The title page is missing from the collection and we have been unable to track it down to date The book’s table of contents identifies the figures in both English and French, and each illustration bears the names of two artists who worked on
it, both of whom would no doubt be surprised to find their art gracing the front cover of a computer programming book two hundred years later
The collection was purchased by a Manning editor at an antiquarian flea ket in the “Garage” on West 26th Street in Manhattan The seller was an American based in Ankara, Turkey, and the transaction took place just as he was packing up his stand for the day The Manning editor did not have on his person the substan-tial amount of cash that was required for the purchase, and a credit card and check were both politely turned down With the seller flying back to Ankara that evening the situation was getting hopeless What was the solution? It turned out to be nothing more than an old-fashioned verbal agreement sealed with a handshake The seller simply proposed that the money be transferred to him by wire and the editor walked out with the bank information on a piece of paper and the portfolio
mar-of images under his arm Needless to say, we transferred the funds the next day, and we remain grateful and impressed by this unknown person’s trust in one of us
It recalls something that might have happened a long time ago
The pictures from the Ottoman collection, like the other illustrations that appear on our covers, bring to life the richness and variety of dress customs of two centuries ago They recall the sense of isolation and distance of that period—and of every other historic period except our own hyperkinetic present Dress codes have changed since then and the diversity by region, so rich at the time, has faded away It is now often hard to tell the inhabitant of one conti-nent from another Perhaps, trying to view it optimistically, we have traded a cul-tural and visual diversity for a more varied personal life Or a more varied and interesting intellectual and technical life
We at Manning celebrate the inventiveness, the initiative, and, yes, the fun of the computer business with book covers based on the rich diversity of regional life
of two centuries ago—brought back to life by the pictures from this collection
Licensed to jonathan zheng <yiyisjun@gmail.com>
Trang 32Part 1
Rethinking the web application
This part of the book introduces the main concepts of Ajax Chapter 1 presents Ajax and reasons to use it Chapter 2 covers the technical fundamen-tals, and shows how they fit together The aim is that, by the end of the book, you’ll be able to tackle real-world projects bigger than a “hello world.” Chap-ter 3 introduces the software development tools that we’ve used to manage large projects, and shows you how to use them with Ajax
Trang 34A new design for the Web
This chapter covers
■ Asynchronous network interactions
and usage patterns
■ The key differences between Ajax
and classic web applications
■ The four fundamental principles of Ajax
■ Ajax in the real world