Tải bản đầy đủ (.pdf) (69 trang)

Ajax in Action phần 1 potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.98 MB, 69 trang )

MANNING
Dave Crane
Eric Pascarello
with Darren James
Ajax in Action
Licensed to jonathan zheng <>

Licensed to jonathan zheng <>
Ajax in Action
DAVE CRANE
ERIC PASCARELLO
WITH DARREN JAMES
MANNING
Greenwich
(74° w. long.)
Licensed to jonathan zheng <>
For 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.
209 Bruce Park Avenue Fax: (203) 661-9018
Greenwich, CT 06830 email:
©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
ISBN 1-932394-61-3
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – VHG – 09 08 07 06 05
Licensed to jonathan zheng <>
To 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.
Licensed to jonathan zheng <>

Licensed to jonathan zheng <>
vii
PART 1 RETHINKING THE WEB APPLICATION 1
1

A new design for the Web 3

2

First steps with Ajax 31
3

Introducing order to Ajax 69
PART 2 CORE TECHNIQUES 117
4

The page as an application 119
5

The role of the server 159
PART 3 PROFESSIONAL AJAX 209
6

The user experience 211
7

Security and Ajax 246
8

Performance 279
brief contents
Licensed to jonathan zheng <>
viii BRIEF CONTENTS
PART 4 AJAX BY EXAMPLE 325
9

Dynamic double combo 327

10

Type-ahead suggest 361
11

The enhanced Ajax web portal 423
12

Live search using XSLT 466
13

Building stand-alone applications with Ajax 503
Licensed to jonathan zheng <>
ix
preface xix
acknowledgments xxi
about this book xxiv
PART 1 RETHINKING THE WEB APPLICATION 1
1
A new design for the Web 3
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
Licensed to jonathan zheng <>
x CONTENTS
1.5 Summary 29
1.6 Resources 30
2
First steps with Ajax 31
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
Introducing order to Ajax 69
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
3.3 Model-View-Controller 91
3.4 Web server MVC 93
The Ajax web server tier without patterns 93

Refactoring the
domain model 96

Separating content from presentation 100
Licensed to jonathan zheng <>
CONTENTS 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
The page as an application 119
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
The role of the server 159
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
Licensed to jonathan zheng <>
xii 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
The user experience 211
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 <>
CONTENTS xiii
6.7 Summary 244
6.8 Resources 245
7
Security and Ajax 246
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
Performance 279
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
Licensed to jonathan zheng <>
xiv CONTENTS
PART 4 AJAX BY EXAMPLE 325
9
Dynamic double combo 327
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
9.5 Advanced issues 343
Allowing multiple-select queries 343
Moving from a double combo to a triple combo 345
9.6 Refactoring 345
New and improved net.ContentLoader 346

Creating a double-combo component 352
9.7 Summary 359
10
Type-ahead suggest 361
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 <>
CONTENTS 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
The enhanced Ajax web portal 423
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
11.6 Refactoring 453
Defining the constructor 455

Adapting the AjaxWindows.js
library 456

Specifying the portal commands 458
Performing the Ajax processing 462
Refactoring debrief 464
11.7 Summary 464
12

Live search using XSLT 466
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
Licensed to jonathan zheng <>
xvi 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
Building stand-alone applications with Ajax 503
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
13.5 Additional functionality 528
Inserting additional feeds 529
Integrating the skipping and pausing functionality 531

Licensed to jonathan zheng <>
CONTENTS 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
B.2 Objects in JavaScript 592
B.3 Methods and functions 606
B.4 Conclusions 617
B.5 Resources 617
appendix C Ajax frameworks and libraries 619
index 635
Licensed to jonathan zheng <>
Licensed to jonathan zheng <>

xix
preface
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.
Licensed to jonathan zheng <>
xx PREFACE
After a few hours of frenzied hacking, I had it working, and I’d even figured out
how to render the new messages in color to make them noticeable to the user.
“What a laugh,” I thought, and turned back to some serious code. Meantime,
unbeknownst to me, Eric Costello, Erik Hatcher, Brent Ashley, and others were
thinking along similar lines, and Microsoft was cooking up the

XMLHttpRequest
for its Outlook Web Access.
Destiny 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 realiz-
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
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.
D

AVE CRANE
Licensed to jonathan zheng <>
xxi
acknowledgments
Although there are only three names on the cover of this book, a legion of tal-
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
to be indispensable, and design editor 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 techni-
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
Licensed to jonathan zheng <>
xxii ACKNOWLEDGMENTS
J.B. Rainsberger provided first-rate technical support at very short notice. We are
truly grateful to them.
We also thank the many reviewers of the manuscript, in its various stages, for
their thoughtful feedback: Ernest Friedman-Hill, Craig Walls, Patrick Peak, J. B.

Rainsberger, Jack Herrington, Erik Hatcher, Oliver Zeigermann, Suresh Kumar,
Mark Chaimungkalanont, Doug Warren, Deiveehan Nallazhagappan, Norman
Richards, Mark Eagle, Christophe Avare, Bill Lynch, Wayland Chan, Shane Wit-
beck, Mike Stenhouse, Frank Zammetti, Brendan Murray, Ryan Cox, Valentin
Crettaz, Thomas Baekdal, Peter-Paul Koch, Venkatt Guhesan, Frank Jania, Mike
Foster, Bear Bibeault, Peter George, Joel Webber, Nikhil Narayana, Harshad
Oak, and Bas Vodde.
Thanks 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.
D
AVE CRANE
I’d like to thank Chia, Ben, and Sophie for their support, wisdom, and enthusi-
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 <>
ACKNOWLEDGMENTS xxiii
language called “Java” ten years ago, and to my brother Mike for figuring out
how to drive our
BBC microcomputer.
E
RIC PASCARELLO
I would like to thank Shona, my wife, for putting up with the late nights and for
planning our wedding without my help, while I wrote this book. Thanks to my
parents for letting me become a computer nerd. Thanks to my co-workers Fred
Grau, Paul Fuseyamore, Tim Stanton, Tracey Baker, Adrienne Cantler, and Kelly
Singleton for putting up with my early morning grumpiness after the long
nights of writing. Thanks to the people at www.JavaRanch.com for their support
and many great ideas. And I cannot forget to thank the aliens who abducted me
and taught me to program.
D
ARREN JAMES
I would like to thank my wife, Alana, and my children, Hannah and Paul, for
being my life’s inspiration. Thanks to my parents for encouraging me to do well
in school; to my colleague and friend, Bill Scott, for his ideas and support; to
Richard Cowin and the contributors to Rico; to Butch Clarke for being an
anchor in the storm; and to Gordon, Junior, and Jub-Jub for making me laugh.
Licensed to jonathan zheng <>
xxiv
about 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 technol-
ogy, either.
Let us explain. Ajax brings together several well-established web technolo-
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
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 cli-
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-
Licensed to jonathan zheng <>

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×