Вы находитесь на странице: 1из 619

I.

WEB-

31

1. Web-

33

2. Ajax

63

3. Ajax

99

II.

145

4. Web-

147

5. Ajax-

135

III. AJAX-

235

6.

237

7. Ajax-

271

8.

303

J A

347

349

381

Y Web- Ajax

439

'" XSLT

479

Ajax,

515

569

Ajax

571

JavaScript -

597

Ajax

625

639

I. WEB-

31

1. Web-

33

1.1.
1.1.1.
1.1.2.
1.1.3.
1.1.4.
1.2. Ajax
1.2.1. ,
1.2.2. ,
1.2.3.
1.2.4.
1.3. Ajax
1.3.1. , Ajax
1.3.2. Google Maps
1.4.
1.4.1. Macromedia Flash
1.4.2.
Java
Web
Start
1.5.
1.6.

34
35
39
42
45
47
47
49
51
53
54
54
55
58
58
59
59
60

2. Ajax
2.1. Ajax
2.2. JavaScript
2.3. CSS
2.3.1. CSS
2.3.2.
2.3.3. CSS

63
64
66
68
68
70
71

2.4. DOM
2.4.1. DOM JavaScript
2.4.2. DOM
2.4.3. DOM
2.4.4.
2.4.5. innerHTML

76
78
80
81
82
83

2.5. XML
2.5.1. IFrame
2.5.2. XmlDocument XMLHttpRequest
2.5.3.
2.5.4.
2.5.5.

84
84
86
89
91
92

2.6. Ajax
2.7.
2.8.

95
97
98

3. Ajax
3.1.
3.1.1.
3.1.2. Ajax
3.1.3.
3.1.4.
3.2.
3.2.1. : Facade Adapter
3.2.2. : Observer
3.2.3. :
Command
3.2.4. :
Singleton

99
100
101
102
102
103
106
107
110
113
116

3.3. "--"

120

3.4. MVC
3.4.1. Ajax,

3.4.2.
3.4.3.

122
123
126
129

3.5.

132

3.5.1. ,
3.5.2.
3.5.3. ,

133
137
140

3.6.

143

3.7.

144

II.

145

4. Web-
4.1. MVC

147
148

4.1.1. MVC
4.1.2. MVC ,

4.2. Ajax-
4.2.1.
4.2.2.

148
149
151
152
157

4.3. Ajax-
4.3.1. JavaScript-
4.3.2. W3C
4.3.3. JavaScript

161
161
164
165

4.4. Ajax-
4.4.1. JavaScript
4.4.2.

169
170
171

4.5.
4.5.1. JavaScript
4.5.2.

173
173
177

4.5.3.

180

4.6.

183

4.7.

183

5. Ajax-
5.1. ,
5.2.

'

185
186
187

5.2.1.
5.2.2. N-
5.2.3.

187
188

5.3.
5.3.1. ,

5.3.2. Model2
5.3.3.
5.3.4. , Web-

190

189

190
192
193
196


5.4. :
5.4.1. ,
5.4.2.
5.4.3. ,
5.4.4. ,
5.4.5. ,

200
201
201
204
207
212

5.5.
5.5.1. HTML-
5.5.2. - XMLHttpRequest
5.5.3.

217
217
219
221

5.6.

230

5.7.

231

I. AJAX-

235

5.
6.1.

237
238

6.1.1.
6.1.2.
6.1.3.
6.1.4.
6.1.5.

239
239
240
241
241

6.2.
6.2.1.
6.2.2. ,

242
242
244

6.3.
6.3.1.
6.3.2.

248
249
251

6.4.
6.4.1.
6.4.2.
6.4.3.

252
252
255
256

6.5.

262

6.6.
6.6.1.
6.6.2. Scriptaculous
6.7.

266
266
268
269

6.8.

270

. Ajax-
7.1. JavaScript
7.1.1. "-"
7.1.2. Ajax-
7.1.3.
7.1.4.

271
272
273
273
274
275

11

7.2.
7.2.1.
7.2.2. Web-
7.3.
7.3.1.
7.3.2. -
7.3.3.
-
7.4. Ajax
7.4.1.
7.4.2. Web
7.5.
7.6.

8.
8.1.
8.2. JavaScript-

276
277
278
288
288
289
291
293
293
297
302
302

304
305

8.2.1.
8.2.2. Venkman
8.2.3. Ajax-
8.3. JavaScript-
8.3.1.
8.3.2. Ajax
8.4.
8.4.1. ,
8.4.2.
8.4.3. 150
8.5.

306
310
313
324
324
327
333
333
337
342
344

8.6.

345

IV. AJAX

347

9.
9.1.

349
350

9.1.1.
9.1.2.
9.1.3. , Ajax
9.2.
9.2.1.
9.2.2. /
9.3. : VB.NET
9.3.1. XML-
9.3.2.
9.4.

350
351
352
353
353
355
356
357
358
360

9.4.1. XML
9.4.2.

361
362

9.5.
9.5.1.
9.5.2.

364
364
365

9.6.
9.6.1. net.ContentLoader
9.6.2.

366
367
372

9.7.

379

0.

381

10.1.
10.1.1.
10.1.2. Google Suggest
10.1.3. Ajax

382
382
384
385

10.2. : #
10.2.1.
10.2.2.

386
386
388

10.3.
10.3.1.HTML
10.3.2. JavaScript
10.3.3.

389
389
390
400

10.4.

410

10.5.
10.5.1. 1: TextSuggest
10.5.2. 2: TextSuggest

10.5.3. 3: Ajax
10.5.4. 4:
10.5.5. 5:

10.5.6.
10.6.

411
412

1. W e b - Ajax

415
418
423
430
437
437
439

11.1.
11.1.1.
11.1.2.

440
440
442

11.2. Java

443

11.3. Ajax
11.3.1.
11.3.2. : Java
11.3.3. ( )

444
445
446
449

13

11.4. DHTML

454

11.4.1.
11.4.2.
11.4.3. JavaScript
11.5.
11.5.1,
11.5.2.

454
455
460
462
463
465

11.6.
11.6.1.
11.6.2. AjaxWindows.js
11.6.3.
11.6.4. Ajax
11.6.5.

468
470
471
473
476
477

11.7.

478

12. "" XSLT


12.1.
12.1.1.
12.1.2.
12.1.3. "" Ajax XSLT
12.1.4.

479
480
480
482
483
484

12-2.
12.2.1.
12.2.2.

485
486
487

12.3. :
12.3.1. XML-
12.3.2. XSLT

488
489
491

12.4. XSL XML


12.4.1. Microsoft Internet Explorer
12.4.2. Mozilla

494
496
496

12.5.
12.5.1.
12.5.2.
12.5.3. XSLT
12.5.4.

497
498
499
501
502

12.6.
12.6.1. XSLTHelper
12.6.2. ""
12.6.3.

12.7.
13. Ajax, 13.1.
13.1.1. XML-
13.1.2. RSS

14

13.2.
13.2.1.
13.2.2. HTML-
13.2.3. CSS-

520
521
522
525

13.3. RSS-
13.3.1.
13.3.2. Ajax

530
530
532

13.4.
13.4.1. ,
13.4.2.
13.4.3. JavaScript

535
536
536
538

13.5.
13.5.1.
13.5.2.

540
540
542

13.6.
13.6.1. Mozilla
13.6.2.

545
545
548

13.7.
13.7.1.
13.7.2.
13.7.3.
13.7.4.

548
549
551
555
567

13.8.

567

569

. Ajax
.1.

571
572

.1.1.
.1.2.
.1.3.

572
574
574

.2. IDE
.2.1.
.2.2.
..
.3.1.
..2. JavaScript
.3.3. HTTP
.3.4. ,

575
575
577
582
582
582
587
589

.4. DOM
.4.1. DOM Inspector Mozilla
.4.2. DOM Internet Explorer
.4.3. Safari DOM Inspector Mac OS X

592
592
594
594

A.5. Firefox

595

.6.

597

15

. JavaScript -
.1. JavaScript Java
.2. JavaScript

597
598
599

.2.1.
.2.2. -,
.2.3.
.2.4.
.2.5. JavaScript-
.2.6.

600
604
606
607
608
610

..
.3.1.
.3.2.
.3.3.
.3.4. Ajax-
.3.5. JavaScript

613
613
615
615
616
620

.4.

623

.5,

623

. Ajax

625
639

, , . ,
1990-, JavaScript.
, , , Java,
.
JavaScript.
1990- , . - ,
,
,
. , JavaScript. ", . ".
.
. ,
Java, ,
JavaScript. , , JavaScript

. ,
(Mike Foster); , .

.
. , ,
.
, . , (Eric Costello), (Erik
Hatcher), (Brent Ashley)
, Microsoft XMLHttpRequest
Outlook Web Access.
.

. Java JavaScript
. , , 1,5 JavaScript-,
t , JSP. , ). , , , [ .
JavaScript . 2005
(James Garrett) " ".
: Ajax ,
, , DHTML. , .
Ajax ;
Prototype, Rico, Dojo, qooxdoo, Sarissa . .
, .
Ajax .
.
. , .
[ ,
.
, , , , Ajax.

, , Ajax, ,
. , , . , ,
Ajax, . Ajax ,
.
, . Ajax Web, . ,
. Ajax -:
. Ajax
. , Ajax, , Ajax Web- .
,
,
JavaScript. Ajax
, , , . , , PHP, Java, C# Visual Basic.
, , ,

26

. ,
, , ,
, .


Ajax ,
.
, ,

.
Web-. Web, " ", , ,
Visual Basic, JavaScript ActionScript. , Web, ,
Web.
Ajax.
. , Web-
, Web. , ,
. , ,
Ajax , , . .
;
. , .


. I , Ajax
. , . II , Ajax, III , .
IV : Ajax.
,
Web-.
, Ajax , .
1 ,
Web-, , -

27

. Ajax Web,
. , Ajax, .
" ", 2.
, Ajax, ,
. , ,
2.
.
Ajax .
3
Ajax. , JavaScript- 1,5 , , Ajax
Web-. . , , ,
Ajax. , .
4 5 Ajax
.
4 . "-".
5
Ajax. Ajax.
6-8 , "" . ,
, . , , ,
, . , .
, , .
7
Ajax-. , Ajax,
Web, , Ajax, Web-.
, Ajax.
, JavaScript- , Web . ,
.

28

8
. , , . , , .
IV 9-13.
Yjax. .1, , : , .
, .
9 HTML-
Ajax. , , ,
5 . ,
.
10.
3 , ..
.
11 Ajax. , ,
, ,
vVeb-. , , , .
, , 1, , ,
1 .
12 Ajax, XSLT L-
.
13 Ajax- , : . -
, ,
RSS.
, , ,
. . , , Ajax, , ,
, J2EE .NET.
Ajax , , . , Ajax , .

29

,
,
, , , JavaScript.
,
Java # .
, Ajax , .
( ) . ,
.


.
. JavaScript, HTML, CSS, XML, Java, C # , Visual Basic
. PHP, .
, , XML-
.
: . . , .


, , ,
http://www.manning.com/crane.
http://www.williamspublishing.com.
, , .NET, J2EE. Linux, Apache,
MySQL, PHP/Python/Perl (LAMP), , . ,
, : Apache, Tomcat IIS. ,
1
" '
. , , .

30


, , .
, ,
.
,
.
.
Web-
. , , ,
. .
,
, .
. :
E-mail:
WWW:

info@williamspublishing.com
h t t p : //www.williamspublishing.com

:
:
115419, , / 783
: 03150, , / 152

I

Web-
, Ajax, 1 Web- . 2 , Ajax,
.
, ,
Hello, World. 3 ,
Ajax-.


Web-

. . .


Ajax
Web-
Ajax
Ajax

1. Web-

"" ,
.

. , , !
.
, ]
. ,
, .

1.1.1.
, (
Web-) ,
.
, ,
.
? . ]
, , <
, , ,
,
, ..
.
, ,
.. (. 1.1).
. ,
?
.

. :
,
(. 1.2). ,
,
.
.
. !
.
, . . 1.3
/.
n-
, , ,
.
,
, . Ajax-
, .. .

" ", .

36

I. Web-

. 1.1. , ,
. ,
,
,

. 1.2. ,
.
,
.
, .

.
. ,

1. Web-

37

. 1.3. / n- .
, .
,
, .
-.
, .
.
(
1990- ) ,
Web- ..
" "

, , , . , , , ,
, . ,
.
Web- . Web-,
. , , Web. , , , . , Web-, , , ,
S t a r t () Windows, .
Web-.
Amazon (. 1.4), .
Amazon .

38

I. Web-

. 1.4. A m a z o n . com.
, : ,

, ,
.

( , ).
: , , , ,
(. 1.5).
, ,
. , . Amazon ,
, , ,
Web- . ,
.
Amazon,
. , , .

1. Web-

39

. 1.5. , A m a z o n . com.
, ,
. , . 1.4.
Web-
,

Web? , .

1.1.2.
,
.
, . , ,
, .
.
, .
, ,
(. 1.6). .

I. Web-

. 1.6. , .
,

. 1.7. , .


, (. 1.7).
, .
: ( ),
. ,
, , , .

1. Web-

41

, , , (.. ).
( HTTP) ( ,
).
,
, ,
. ,
. ;
.
, .
, Java Microsoft
.NET Framework, . (RPC) ,
, .
, , . , - ,
.
, .
, ? , .
- .

. ,
.
, ,
, . , ,
,
. .
- , , ,
, , , , , . ,

.

42

I. Web-

. 1.8. , .
.
. ,

1.1.3.
, ,
. ,
, . ,
, , . .
. , .
(. 1.8).
, . ,
. , ,
.
, .
", , ?" .

1. Web-

43

. 1.9. ,
. , ,
,
.
; , ,

,
. . , ,
" ", , ,
(.. ). , , , ,
(. 1.9).

, ;
. , ,
, ,
. ,
.
, . , , /.
, "" ,
. , , Web-

44

I. Web-

. , , ,
.
, , Web-, - . HTTP
"-". ,
, ,
, , ,
, ,
. , "", "". , . , .
Web-
, Java, PHP .NET,
. ,
, . HTTP ,
, , , .
:
. HTTP Web-
.
Web-, ,
Amazon, Web-. , , ,
.
. Amazon , .
. WYSIWYG Web Web-. ,
, . Web- ,
,
.
Amazon, , ,
. Web-
. , Web-
Amazon, , .

1. Web-

45

1.1.4.
, : . : , ,
. ,
.
, , , ,
, .
.
(Alan Cooper), ,
. :
(transient) (sovereign). , , , ,
. , , , .
. , , .
, (
, ), (
), , . ,
, . , .
, . . , , , - ,
. - ,
.

, .
Web- Amazon . eBay, Google Web. , ,
Web. , . Web- ,
.

46

I. Web-

. 1.10.

, Web- , .
Web
,
. ( Web ,
www.webhistory.org/www.lists/www-talk.1993ql/0182.html.
, 1993
- , HTML
, .)

JavaScript .
.
Ajax " "
" " , . , JavaScript " " , Web-,
.
. , .
.
, . ,
, , . , , " ". ,
. , : ,
, . (. 1.10).

1. Web-

47

Web. ,
Ajax, Web- - . Ajax Web-
,
" " . Ajax,
Web-, , ,
. Ajax, Web .

1.2. Ajax
Web- , . , , ,
Ajax.

1.2.1. ,
Web-
. , . , , , .
Java .NET,
, MIME-, API. . 1.11
Web-.

, . ,
, "" .
.
HTML-,
, .
,
, .
.
: , , .
,
, , . ,
, . Ajax (. 1.12).

48

I. Web-

. 1.11. Web-.
""
Web-, .


. . , ,
.

, JavaScript. ; ,
, . , ,
, , ( )
.

1. Web-

49

. 1.12. Ajax-

, . ,
"" , .

1.2.2. ,
, Web
. "", , ,
. . 1.13, , ,
.
Ajax- "" "" . , ,
,
.

50 I. Web-

()

()
I

()

. 1.13. , Web-
() Ajax- (). ()
Web- , Ajax-

1. Web-

51

Ajax- ,
, JavaScript-, ,
XML-.
5. , , , Web-.
, Ajax-, , , . .
, Web-,
, Ajax-. Ajax , .

12.3.

Web- : HTML-.

CGI (Common Gateway Interface ).
CSS (Cascading Style
Sheets ) , ,
. Web- ,
.
, , : ,
, . . , ,
. , , URL, .
JavaScript. Web-
JavaScript-, . , , , .
, . JavaScript-
, Web-.

.
; -

52

I. Web-

, . ,
, , , . , . , "" , ,
, " " " " " ".
, "" , Ajax-. Ajax
, "" , . ,
, .
, "" ;
. ,
, . "" , . "" ,
, .
(. 1.14). , Ajax,
.
, , , , ,
, .
Ajax , , .
, Web , . ,
, ,
.
Web-,
, . . , ,
. Google Suggest
( h t t p : //www. google. com/webhp?complete=l).
, . , .

1. Web-

53

. 1.14. .
:
, .
,
,

,
. 8.

1.2.4.
Web- JavaScript-.

, . JavaScript ,
.
Ajax- ,
. , , ,

. , ,
. , .
,
.
, , , Web. .

. , , ,

54

I. Web-

, .
Ajax-
. , "" Web-,
, " ". , Web-.

1.3. Ajax
. Ajax
, . , ,
,
.
Ajax,
.

1.3.1. , Ajax
Ajax Google. ( , Ajax.) - GMail
2004 .
, , , .
,
. GMail Web- , Microsoft Outlook Lotus Notes, ,
GMail , ActiveX Java-.
,
, .
GMail , , Google
Suggest,
, , Google Maps , . . Flickr, Yahoo!.
, ,
. Ajax-, -

1. Web-

55

3,
.
, Ajax, ,
. , , , Google Yahoo!,
, .
Ajax, . Google Maps ,
.

1.3.2. Google Maps


Google Maps
.
(. 1.15), 1 . ;
, (. 1.16).
Web-,
,
Ajax. , ,
; , , .
Google Maps. . , , , .
:
, . ,
. , ,
, .
, . -, , ,
.
, ; , . , - . -, , ,
,
, .

1
Google Earth,
. . .

56

I. Web-

:ile Edit Siew So Bookmarks Iools Help


| '<: $ 4? PjH SL Mtp //maps google com/
j Firefox Help _j Firefox Support . Ping-in FAQ
Maps

Map
)

>

Drag the mop with moose, or


double cbck to center.
Example

---

" T -1-

f i t , .

searches:

Go to a locution
"kansasoly"
trvfr.
"10 market st, san fraadsce* laaJt

p^

Find e business
"hotels near
tax*
try it
""
try it
Get dh actions
"jB( to 350 bth. new york. ny" try it
"sertile to 98109"
try it

Take a 0 t i r
Use our new Satellite feature? Try
KavhoU Goose's 3D Earth.

Done

. 1.15. Google Maps


, Google. ,
,
,

.
, Ajax, ,
. , , , .
, Web- .
.
Google Maps, ,
, .
,
. , Ajax, ,
, .
.

1. Web-

57

!e Ed* View So Bookmarks Iools Help

^i

# * mg

Q Firefox Help

cf!

sCl http //maps google com/

Q Firefox Support

Go

U Plug-in FAQ

Maps Local Search Directions


i

'"'

" " '

p o t e l s

l a x

Map

Q Pnnt 1 Email m> [ink to this paqa


C

R a d i s s o n Lax
(310) 670 9000 - 0 2

Courtyard by Marriott:
T o r r a n c e Plaza
(310) 533-8000 -0.2 mi E

C o u r t y a r d b v M a r r i o t t : Lax
(310)649-1400- 03 m

Sheraton Gateway
(310)642-1111 -04 mil
Crowne Plaza Los Angeles
Airport
(310) 642-7500-05 ire F
Vagabond Inn
(415) 776-7500- OS nsF
1
{

ft S t a r w o o d H o t e l s &
T Resorts
(310) 348-1800 -OVmiE
M a n d a r i n Oriental H o t e l
Group
(310) 670-6422 - 0 m F

Map dsta 2005 NAV1EQ

^ E m b a s s y Suites Hotel

http jtmaps google com/

. 1.16. Google Maps.


DHTML .
Ajax

Web- , Google
Maps , , , . ( ,
.) , Google, , ,
. , . , Ajax, Google
. , , ,
Ajax , .

58

I. Web-

, Ajax . ,
Ajax- . , . , ,
.

1.4.
Ajax , . Ajax .
.
.

1.4.1. Macromedia Flash


Macromedia Flash , . . Flash , . .
ActionScript , JavaScript. , . Flash
-. , , ,
Ajax.
Flash
. , ,
, , , Flash,
.
Windows, Mac OS X Linux,
, Linux, .
Flash : Macromedia Flex Laszlo.
,
-, J2EE
(Java 2 Enterprise Edition).
Flash , PHP- libswf.

1. Web-
1.4.2.

Java

Web

59

Start

Java Web Start , Web-, Java. ,


, , . ,
; , Web Start. Web Start
Java. Internet Explorer Mozilla
.
Web Start ""
.
. . ,
, , .
Web Start Java Swing. Web Start SWT (Standard Widget Toolkit), Eclipse,
, .
.NET
No Touch Deployment. ,
.
. , , Flash Ajax
. ( Ajax .) Java .NET ,
Web-,
, .

1.5.
. , ,
, , , , ,
,
, . , , ,

.

60

I. Web-

/ n- , , , ,
.
, , , , "", Web-,
.
Ajax , : Web- ,
, . , .
,
Web- . ,
, , .
, .
, .
,
.
, , .
,
.
Ajax
. ,
.

1.6.
, ,
.
Ajax 18 2005 . , h t t p : / /
www.adaptivepath.com/publications/essays/archives/000385.php.
.
: http://www.cooper.com/articles/
art_your_programs_posture.htm.

1. Web-

61

Google Maps .
: http://maps.google.com
: http://maps.google.co.uk
, : h t t p : / /moon. google. com2
Web- Pedaling History, http://www.pedalinghistory.com.

Google Earth http://earth.google.com/. . .

. . .
, Ajax


Document Object Model



XMLHttpRequest

Ajax

64

I. Web-

1 , Ajax
.
, , , Ajax , , .
,
, .
Ajax,
Ajax , , .
, , "Hello, World!".
, . 3.
, Ajax, . Ajax
Web-, .

2.1. Ajax
Ajax ,
, (. 2.1).
1 , Ajax-
. JavaScript-, "" ,
- .
DOM (Document Object Model), , , . , . , CSS (Cascading Style
Sheets),
DOM-. XMLHttpRequest ( ) ,

. Ajax . 2.1.
CSS, DOM JavaScript DHTML (Dynamic HTML). , DHTML,
1997 , , . DHTML Web- ,

. , , . DHTML Ajax,
,
Web-.

2. Ajax

65

2.1. Ajax
JavaScript

JavaScript ,
Web-.
JavaScript Web-

.
Ajax-

CSS (Cascading Style Sheets)

CSS
Web-.

. Ajax CSS

DOM (Document Object Model)

DOM Web-
,
JavaScript.
Ajax-

XMLHttpRequest

XMLHttpRequest
Web- .
,
XML,
.
XMLHttpRequest
,
,
.

, ,
Microsoft Internet Explorer, Mozilla/Gecko, Firefox, Mozilla Suite,
Netscape Navigator, Camino, Opera, Apple Safari Konqueror ( Unix KDE). ,
, ,
. , , , .
.
, Ajax-.
Java .NET .

Ajax-. ,
Ajax ,
Ajax-. Ajax
.

66

I. Web-

. 2.1. Ajax. JavaScript


- . Document Object Model

,
.
X M L H t t p R e q u e s t

Ajax, ,
. Web-, , ,
. 3,
.
, Ajax, JavaScript.

2.2. JavaScript
Ajax JavaScript. Ajax , , , .
JavaScript. .
JavaScript . , , .

2. Ajax

67

. ,
.
a r =3.1415926;
x-'pi-">

,
.
"" ,
. . JavaScript- Web- . .
var x=eval('7*5');
, . eval ()
, JavaScript-, , . , ,
.
" " , . JavaScript
, , , , ,
, ,
( , ). ,
. JavaScript ,
.
, Web-, JavaScript CSS, DOM XMLHttpRequest. Web .
, , JavaScript .
JavaScript.

, ,
, Java. JavaScript- , .
, JavaScript (
).
, Ajax, JavaScript
,
. , Ajax-,
JavaScript. He , Ajax.
, Web-.

68

I. Web-

2.3. CSS
, CSS, Ajax,
Web-. CSS Web-.
, , , , , , .
Web-
Web-.
Ajax,
.
, .
CSS,
, CSS.
CSS , . , Web-.
,
.
: .
, , , . ,
, (
<1>) .
:
hi { color: red }
. ,
<1>. ;
. ,
. . .

2.3.1. CSS
HTML-, , . : HTML-,
.
, . , <1>, <DIV>,
:
div hi { color: red; }
,
, DOM, -

2. Ajax

69

. ,
HTML-. , ,
callout, ,
:
.callout { border: solid blue lpx; background-color: cyan }
, HTML class:
<div>I'll appear as a normal b i t of text</div>
<div class='callout'>And I ' l l appear as a callout!</div>
. ,
loud :
.loud { color: orange }
, ,
loud c a l l o u t , .
<div c l a s s = ' l o u d ' > I ' l l be bright orange</div>
<div c l a s s = ' c a l l o u t ' > I ' 1 1 appear as a callout</div>
<div class='callout loud'>
And I ' l l appear as an unappealing mixture of both!
, <div>,
.
, CSS.
, ,
. :
span.highlight { background-color: yellow }
<span>, h i g h l i g h t . <span> , c l a s s = ' h i g h l i g h t ' , .
.
div.prose span.highlight { background-color: yellow }
<span> highlight,
<div> prose.
, , . id.
, ,
.
,
, , :
#close { color: red }

I. Web-

70

CSS . . , .
*:first-letter {
font-size: 500%;
color: red;
float: left;
J

:
p.illuminated:first-letter {
font-size: 500%;
color: red;
float: left;
}
<> illuminated. f i r s t - l i n e hover.
, .
,
, :
a:hover{ color:yellow; }

. , ,
. .

2.3.2.
HTML- .
, <DIV>, . .
, ,
"" .
, .
, - ,
:
.robotic{
font-size: 14pt;
font-family: courier new, courier, monospace;
font-weight: bold;
color: gray;

2. cAjax

71

, .
.robotic{
font: bold 14pt courier new, courier, monospace;
color: gray;
}
"", .
CSS ,
.
.padded{ padding: 4px; }
.eccentricPadded {
p a d d i n g - b o t t o m : 8;
p a d d i n g - t o p : 2;
p a d d i n g - l e f t : 2;
p a d d i n g - r i g h t : 1;
margin: lpx;
}

width height. . top l e f t . .


background-color.
, ,
background-image.
. t i t l e b a r { background-image: url(images/topbar.png); }
v i s i b i l i t y : h i d d e n
display:none. v i s i b i l i t y : h i d d e n , , - , a display:none .
, Ajax-, ,
CSS .

2.3.3. CSS
CSS Web, , Ajax-,
, , . . 2.2 , CSS.
CSS , , ,
. 2.2. .

72

I. Web-

. 2.2. CSS .
HTML-; .
,

CSS
.
, , .
div.window{
position: absolute;
overflow: auto;
margin: 8px;
padding: Opx;
width: 42Opx;
height: 28Opx;
}

, ,
float, . .
div.item{
position: relative;
height: 64px;
width: 5 6px;
float: left;
padding: Opx;
margin: 8px;
}

itemName, item, ,
. , .
div.item div.itemName{
margin-top: 48px;
font: lOpx verdana, arial, helvetica;
text-align: center;

2. Ajax

73

CSS
, CSS,
.
, :
div.folder {
background:
transparent url(images/folder.png)
top l e f t no-repeat;
}
div.filet
background:
transparent url(images/file.png)
top left no-repeat;
}
div.special{
background:
transparent url(images/folder_important.png)
top l e f t no-repeat;
}

background , . , . (, . 2.2, Firefox. Internet Explorer .png; .


, , .
, , .gif.)
.
, . :
<div class='item folder'>
<div class='itemName'>stuff</div>
<div c l a s s = ' i t e m
<div class='itemName'>shopping l i s t < / d i v >

.
, ,
. .
div.titlebar{
b a c k g r o u n d - c o l o r : #0066;
background-image: u r l ( i m a g e s / t i t l e b a r _ b g . p n g ) ;
background-repeat: repeat-x;

HTML- 2.1.

74 I. Web-
2.1. window.html
<htmixhead>
< ! >
<link rel='stylesheet' type='text/ess'
h r e f = ' w i n d o w . e s s ' />
</head>
<body>
< ! >
<div class='window'>
<div c l a s s = ' t i t l e b a r ' >
< ! >
<span c l a s s = ' t i t l e B u t t o n ' i d = ' c l o s e ' X / s p a n >
<span c l a s s = ' t i t l e B u t t o n ' i d = ' m a x ' X / s p a n >
<span c l a s s = ' t i t l e B u t t o n ' id='min'></span>
<div c l a s s = ' c o n t e n t s ' >
<div c l a s s = ' i t e m f o l d e r ' >
<div class='itemName'>Documents</div>
<div c l a s s = ' i t e m f o l d e r ' >
<div c l a s s = ' i t e m N a m e ' > l o s t and found</div>
< ! >
<div c l a s s = ' i t e m folder'>
<div class='itemNamel>stuff</div>

<div class='item
<div class='itemName'>shopping list</div>
<div class='item
<div class='itemName'>things.txt</div>
<div class='item special'>
<div class='itemName'>faves</div>
<div class='item
<div class='itemName'>chapter 2</div>
</body>
</html>
HTML- , . ,
. ,
. HTML-,
, , , , . ,
, .
. 2.2. 2.2.

2. Ajax

2.2. window.ss
div.window{
position: absolute;
overflow: auto;
background-color: feeefff;
border: solid #0066aa 2px;
margin: 8px;
padding: Opx;
/* 1 */
width: 42Opx;
height: 280px;
}
div.titlebar{
/* 2 */
background-color: #0066aa;
background-image:
url(images/titlebar_bg.png);
background-repeat: repeat-x;
color:white;
border-bottom: solid black lpx;
width: 100%;
height: 16px;
overflow:hidden;
}
span.titleButton{
position: relative;
height: 16px;
width: 16px;
padding: Opx;
margin: Opx lpx; Opx lpx;
/* 3 */
float:right;
}
span.titleButtonfmin{
background: transparent
url(images/min.png) top left no-repeat;
}
span.titleButton#max{
background: transparent
url(images/max.png) top left no-repeat;
}
span.titleButton#close{
background: transparent
url(images/close.png) top left no-repeat;
}
div.contents {
background-color: #e0e4e8;
overflow: auto;
padding: 2px;
height:240px;
}
div.item{
position : relative;
height : 64px;
width: 56px;
float: left;

75

I. Web-
color : #004488;
font-size: 18;
padding: ;
margin: 4px;
}
div.item div.itemName {
/* 4 */
margin-top: 48;
font: 10px verdana, arial, helvetica;
text-align: center;
}
div.folder{
background: transparent
url(images/folder.png) top left no-repeat;
}
div.file{
background: t r a n s p a r e n t
url(images/file.png) top left no-repeat;
}
div.special{
background: t r a n s p a r e n t
url(images/folder_important.png)
top l e f t no-repeat;

,

. ,
CSS: , , .
CSS Web-. ,
Web, ,
Ajax-.

\.
(Document Object Model) (Web-)
JavaScript. DOM (. 2.3) .
Ajax-. Web , HTML-. , . Ajax DOM. HTML- Web- . HTML,
. BODY, -

2. Ajax

77

. 2.3. HTML-
DOM ,
HTML-

. , ,
. , ,
, .
DOM- Web- , , , , .. JavaScript Web document,
DOM-. DOM
W3C. , ,
, , (.. ,
, ). . 2.3 , 2.2.
Mozilla DOM Inspector (

78

I. Web-

).
DOM HTML-
. DOM HTML , , .
DOM " ". , DOM JavaScript, ,
.

2.4.1 DOM JavaScript


. , , ,
( ). :
, . DOM,
HTML- ( , Web-).
, 2.2 . 2.3, . DOM . , .
,
,
. DOM, ,
. 2.3 HTML- Web-.
2.3. Ajax- h e l l o
<html>
<head>
< ! >
<link rel='stylesheet' type='text/ess'
h r e f h e l l o . e s s 1 />
< ! J a v a S c r i p t - >
<script
type='text/javascript'
src='hello.j s'></script>
</head>
<body>
<p i d = ' h e l l o ' > h e l l o < / p >
<! >
<div i d = ' e m p t y ' x / d i v >
</body>
</html>

: , JavaScript- .
div .
5 .
, . CSS- ,

2.

79

. CSS- 2.4.
2.4. h e l l o .css
.declared{
color: red;
font-family: arial;
font-weight: normal;
font-size: 16px;
}
.programmed!
color: blue;
font-family: helvetica;
font-weight: bold;
font-size: lOpx;

DOM-. (
. ,
, fred jim.) HTML, . 2.5 JavaScript- , 2.4. , DOM-.
2.5. h e l l o . j s
window.onload=function(){
//
var hello=document.getElementById('hello') ;
hello.className='declared' ;
var empty=document.getElementById('empty' );
addNode(empty,"reader of") ;
addNode(empty, "Ajax in Action!");
var children=empty.childNodes;
for (var i=0;i<children.length;i++){
children[i].className='programmed' ;
}
//
empty.style.border='solid green 2px';
empty.style.width="200px";
}
function addNode(el,text){
//
var childEl=document.createElement("div");
el.appendChild(childEl);
//
var txtNode=document.createTextNode(text);
childEl.appendChild(txtNode);

80

I. Web-

JavaScript , HTML- .
window.onload(),
.
DOM , .
2.5 , DOM. , , DOM-
. ( ,
),
, .

2.4.2. DOM
, , DOM
JavaScript-, , .
, document. DOM ( ) document.
. , .
. onloadO, 2.5, : , ,
<div>, . id
.
< i d = ' h e l l o ' >

<div id='empty ></div>


DOM-
, .
var hello=document.getElementById('hello') ;
, Document.
, ,
Document document. IFrame Document,
, .
DOM. DOM , . parentNode childNodes. parentNode DOM,
a childNodes JavaScript- , .

2. Ajax

81

var children=empty.childNodes;
for (var i = 0 ; K c h i l d r e n . l e n g t h ; i + + ) {

,
-: getElementsByTagName.
, document.getElementsByTagName("UL") UL, .
, . , getElementByld , getElementsByTagName (), , .

2.4.3. DOM
, (,
). JavaScript- DOM
.
2.5. empty
. , . addNode () document .createElement() document.createTextNode(). c r e a t e E l e ment (), , HTML-.
var childEl=document.createElement("div") ;
createTextNode () DOM-, . ,
div, .
var txtNode=document.createTextNode("some t e x t " ) ;
DOM , HTML-. ,
, . , , DOM.
, . appendChild().
el.appendChild(childEl) ;
createElement(), createTextNode() appendChild() .
. , .

82

I. Web-

2.4.4.
, ,
HTML-. ,
, , , .
DOM, , , , , ,
. , .
Web- , JavaScript-.
.
className
,
className DOM.
, ,
declared.
hello.className='declared' ;
h e l l o DOM.
CSS .
style
, .. , CSS.
DOM s t y l e , , .
. 2.4, DOM- . , className s t y l e .
s t y l e . , empty, .
empty.style.border="solid green 2px"; empty.style.width="200px";
box
className,
. , .
, 1 800 .
, DOM . , .
Web- . innerHTML.

2. Ajax

83

. 2.4. , s t y l e DOM-
DOM Inspector. .
:

2.4.5. innerHTML
D0M . createElement () appendChild()
, . innerHTML DOM-. . innerHTML ,
HTML. , addNode
:
function addListItemUsingInnerHTML(el,text){
el.innerHTML+="<div class='programmed 1 >"+text+"</div>";
}
div . ,
, +=.
innerHTML, . innerHTML

84

I. Web-

.
, .
JavaScript, CSS DOM, Dynamic HTML. , Ajax
, Dynamic HTML, , , .
, Ajax DHTML, .

2.5. XML
, ,
, . 1 , .

,
.
, ,
, . , ,
HTTP- ,
. Web-

Web-,
.
,
,
; .
I Frame.
XMLHttpRequest. .

2.5.1. IFrame
Netscape Navigator Microsoft Internet Explorer DHTML, Web- .
HTML I Frame.
inline (), ..
, "". IFrame DOM, , ,
, . , I Frame

2. Ajax

85

. 2.5. ,
.
( I F r a m e
X M L H t t p R e q u e s t ) . ,
(
).

, . , , , Web-. ,
, ,
. . 2.5 ,
.
DOM, IFrame HTML- , document . createElement (). , IFrame ,
, document. getElementByld(), 2.6.
2.6. IFrame
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
var iframe=document.getElementById('dataFeed') ;
var src='datafeeds/mydata.xml';
loadDataAsynchronously(iframe,src)
;
function

loadDataAsynchronously(iframe,src){

86

I. Web-
//
}
</script>
</head>
<body>
< ! >
<iframe
id='dataFeed'
style='height:Opx;width:Opx;'
>
</iframe>
</body>
</html>

IFrame ,
. display:none,
. , IFrame , .. getElementByldO
window, onload. IFrame
, 2.7. ,
, , DOM
HTML-.
2.7. IFrame
function fetchData(){
var iframe=document.createElement('iframe') ;
iframe.className='hiddenDataFeed' ;
document.body.appendChild(iframe);
var src='datafeeds/mydata.xml';
loadDataAsynchronously(iframe,src);

createElement appendChild,
DOM, . , IFrame.
.
, 3, , , .
, ,
.

2.5.2. XmlDocument XMLHttpRequest


IFrame
, ,

2. c Ajax

87

. Web-
, . IFrame.
XmlDocument XMLHttpRequest,
DOM, .
,
.
ActiveX, Internet
Explorer JavaScript.
, . XmlDocument XMLHttpRequest ,
XMLHttpRequest .
,
XmlDocument, XMLHttpRequest. 2.8 ,
XmlDocument.
2.8. getXMLDocument ()
function getXMLDocument(){
var xDoc=null;
if (document.implementation
S & document.implementation.createDocument){
xDoc=document.implementation
// Mozilla/Safari
.createDocument("","",null);
}else if (typeof ActiveXObject != "undefined"){
var msXmlAx==null;
try{
msXmlAx=new ActiveXObject
// Internet Explorer
("Msxml2.DOMDocument");
}catch (e){
msXmlAx=new ActiveXObject
// Internet Explorer
("Msxml.DOMDocument");
xDoc=msXmlAx;
}
if (xDoc==null M typeof xDoc.load=="undefined"){
xDoc=null;
}
return xDoc;

__}

__

XmlDocument API,
.
.

88

I. Web-

, ,
XmlDocument ( Mozilla Safari). , ActiveX
, ( Microsoft).
, . MSXML 2.
. .
, . ,
. getXmlDocument () ,
, .
, (object detection), ,
,
.
2.9 , , XMLHttpRequest.
2.9. getXMLHTTPRequest ()
function getXMLHTTPRequest() {
var xRequest=null;
if (window.XMLHttpRequest) {
// Mozilla/Safari
xRequest=new XMLHttpRequest();
}else if (typeof ActiveXObject != "undefined"){
xRequest=new ActiveXObject
// Internet Explorer
("Microsoft.XMLHTTP");
return xRequest;

:
, , XMLHttpRequest. , ActiveX. , n u l l .
6.
, , . .

2. Ajax

89

2.5.3.
XMLHttpRequest . ,
, URL ,
. ,
.
function sendRequest(url,params,HttpMethod){
if (IHttpMethod){
HttpMethod="POST";}
var req=getXMLHTTPRequest();
if (req){
req.open(HttpMethod,url,true);
req.setRequestHeader
("Content-Type", "application/x-www-form-urlencoded");
req.send(params);
}
}
XMLHttpRequest
HTTP,
. ( CGI-, ServletRequest .) HTTP,
, , , .
HTTP
HTTP , . Web- ,
, method . Ajax, ,
HTTP, .
HTTP- , . (, , , , , Web-.) , ; ,
. , ,
. ,
.
HTTP- ,
.
HTML- , . Mozilla LiveHTTPHeaders (.
). .
Google , .

90

I. Web-

:
GET / HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/5.0
(Windows; U; Windows NT 5.0; en-US; rv:1.7)
Gecko/20040803 Firefox/0.9.3
Accept: text/xml,application/xml,
application/xhtml+xml,text/html;q=0.9,
text/plain;q=O.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: PREF=ID=cabd38877dc0b6al:TM=1116601572
:LM=1116601572:S=GD3SsQk3v0adtSBP
, HTTP-
. Web- GET POST. GET , a POST
, HTML-. , W3C (World Wide Web
Consortium), , , HEAD,
; PUT, ; DELETE, .
, , ,
. Google,
cookie .
.
HTTP/1.x 302 Found
Location: http://www.google.co.uk/cxfer?c=PREF%3D:
TM%3D1116601572:S%3DzFxPsBpXhZzknVMF&prev=/
Set-Cookie: PREF=ID=cabd38877dc0b6al:CR=1:TM=1116601572:
LM=1116943140:S=fRfhD-u49xp9UE18;
expires=Sun, 17-Jan-2038 19:14:07 GMT;
path=/; domain=.google.com
Content-Type: text/html
Server: GWS/2.1
Transfer-Encoding: chunked
Content-Encoding: gzip
Date: Tue, 24 May 2005 17:59:00 GMT
Cache-Control: private, x-gzip-ok=""
. 302
. cookie , (MIME-).
, .
:
H T T P / l . x 200
Cache-Control: p r i v a t e

2. cAjax

91

Content-Type: text/html
Content-Encoding: gzip
S e r v e r : GWS/2.1
C o n t e n t - L e n g t h : 1196
D a t e : Tue, 24 May 2005 1 7 : 5 9 : 0 0 GMT

200 , Google,
. content-type ,
HTML.
sendRequest . POST, .
, , , .
,
, ?

2.5.4.

,
. , , . ,
window.onload.
, ( ). , .
. JavaScript-
, onkeypress, onmouseover .
onload onreadystatechange.
onreadystatechange Internet Explorer Mozilla, .
( Mozilla onload,
.) ,
, 2.10.
2.10. ,
var
var
var
var
var

READY_STATE_UNINITIALIZED=O;
READY_STATE_LOADING=1;
READY_STATE_LOADED=2;
READY_STATE_INTERACTIVE=3;
READY_STATE_COMPLETE=4;

92

I. Web-
var req;
function sendRequest(url,params,HttpMethod){
if (!HttpMethod){
HttpMethod="GET";
}
req=getXMLHTTPRequest();
if (req){
req.onreadystatechange=onReadyStateChange;
req.open(HttpMethod,url,true);
req.setRequestHeader
("Content-Type", "application/x-www-form-urlencoded");
req.send(params);
}
}
function onReadyStateChange(){
var ready=req.readyState;
var data=null;
i f (ready==READY_STATE_COMPLETE){
data=req.responseText;
}else{
data="loading...["+ready+"]";
}
II... ...

sendRequest (), . ,
. ,
onReadyStateChange().
readyState . , . 4, .
, . XMLHttpRequest, ,
,
. 3.1.
.

2.5.5.
, . HTML, JavaScript-, 2.11.
XMLHttpRequest, , , ,
.
DOM console, .

2. Ajax 93

2.11. XMLHTTPRequest
<html>
<head>
<script type='text/javascript'>
var req=null;
var console=null;
var READY_STATE_UNINITIALIZED=O;
var READY_STATE_LOADING=1 ;
var READY_STATE_L0ADED=2 ;
var READY_STATE_INTERACTIVE=3;
var READY_STATE_COMPLETE=4;
function sendRequest(url,params,HttpMethod){
if (!HttpMethod){
HttpMethod="GET";
}
req=initXMLHTTPRequest() ;
if (req){
req.onreadystatechange=onReadyState;
req.open(HttpMethod,url,true);
req.setRequestHeader
("Content-Type", "application/x-www-form-urlencoded");
req.send(params);
}
}
function initXMLHTTPRequest(){
var xRequest=null;
//
if (window.XMLHttpRequest){
xRequest=new XMLHttpRequest();
} else if (window.ActiveXObject){
xRequest=new ActiveXObject
("Microsoft.XMLHTTP");
}
return xRequest;
}
//
function onReadyState(){
var ready=req.readyState;
var data=null;
// readyState
i f (ready==READY_STATE_COMPLETE){
//
data=req.responseText;
}else{
data="loading...["+ready+"]";
}
toConsole(data);
}
function toConsole(data){
if (console!=null){
var newline=document.createElement("div");
console.appendChild(newline) ;
var txt=document.createTextNode(data) ;
newline.appendChild(txt) ;
}

94

I. Web-

window.onload=function(){
console=document.getElementById('console1)
sendRequest("data.txt");
}
</script>
</head>
<body>
<div id='console'X/div>
</body>
</html>

, Microsoft Internet Explorer Mozilla Firefox. ,


readyState , . , readyState ( ).
, Microsoft Internet Explorer.
loading...[1]
loading...[1]
loading...[3]
Here is some text from the server!
.
, READY_STATE_INTERACTIVE ( ). ; .
, Mozilla Firefox 1.0.
loading...[1]
loading...[1]
loading...[2]
loading...[3]
Here is some text from the server!
, , readyState 2.
,
aresponseText XMLHttpRequest.
,
, responseXML. MIME- text/xml, DOM,
, getElementByld childNodes,
2.4.1.
" " Ajax, , Ajax .

2. Ajax

95

2.6. Ajax
CSS, DOM, JavaScript Ajax,
.
1 Web , , Ajax. . Web- , ,
, .
. .
Ajax
, . , .
, , . Web-
, CSS, DOM, JavaScript . JavaScript- ,
Web-. , Ajax.
Ajax Web- , ,
.
Web ,
,
.
, Ajax
, , Web-. Ajax
Web-
.
, , . ,
Web- "", ,
(. 2.6). Ajax
Google . Google
Suggest Google Maps
.

96

I. Web-

. 2.6. Ajax-,
Web- "",

Ajax , , ,
(. 2.7). ,
,
. Google
GMail,
.
. Ajax , ,
. Web-
- ,
. ,
, .
, ,
, .
HTML ?

HTML-? , ,
- ? -

2. cAjax

97

. 2.7. Ajax-,
, ,
.

,
. .

2.7.
Ajax.
JavaScript ,
,
, .
, , ,
, JavaScript
.
CSS DOM , . ,
Ajax- (
3 4).
, XMLHttpRequest
: XmlDocument IFrame. -

98

I. Web-

XMLHttpRequest, . I Frame ,
. , , Web-. 5
.
, Ajax,
, . Ajax , ,
, Web-, .
, "" .
Ajax ,
JavaScript-,
. , ,
, . Ajax-.

2.8.
, , CSS Zen Garden (http://www.csszengarden.com/), , , CSS.
(Eric Meyer) CSS. Web http://www.meyerweb.com/eric/css/. Blooberry ( h t t p : / /
www.blooberry.com) , CSS.
Ajax, IFrame,
http://developer.apple.com/internet/webcontent
/iframe.html.
Mozilla LiveHttpHeaders h t t p : / /
livehttpheaders.mozdev.org/.
(Danny Goodman) Dynamic HTML: The Definitive Reference (O'Reilly, 2002) JavaScript Bible (John Wiley, 2004)
D0M. , .
Web- W3Schools (http://www.w3schools.com/js/js_examples_3.
asp) JavaScript.

. . .
Ajax
JavaScript- Ajax-

Ajax-
"-"
Ajax-
Ajax

100

I. Web-

2 , Ajax. , , , Ajax-, . ,
, HTML-
, . ,

. . ,
, .
, , .
!
,
.
.
,
Ajax-,
.
Ajax DHTML , . Ajax- JavaScript-, . ,
. , , , DHTML.
, . Ajax-, . , 9, ,
. , 4-6,
. , , JavaScript-,
, .
,
Ajax, , 3.5.

3.1.
, , (refactoring), .. , , . , , , .

3. Ajax

101

, , .
, , ,
, ,
- .
. ,
.
. , .
2,
JavaScript, HTML- . JavaScript- , 120 (,
) ,
. JavaScript-
( ) . , ,
.
,
(separation of responsibilities).

.
.

3.1.1.
, , , , . .
, ,
, .
, ,
. 1970- ,
. Java, , Microsoft .NET Framework. , , " ", ,
-, ,
, . . , .
,
.

102

I. Web-

,
. "
,
" , , .
,
Command, .
Java,
, , , . , , , -.
: Ajax? : ! ,
, Ajax.

3.1.2. Ajax
, Ajax-, ,
JavaScript-,
.
Web- PHP, Java .NET.
Ajax, .
, JavaScript- , , Java # .
, JavaScript , Ruby, Python Common Lisp, Java # .
. ,
,
. , , Java # , ,
, .
JavaScript
, Web-, ,
. Ajax- ,
, "" , Java # .

3.1.3.
, , , , , .
, . ,

3. Ajax

103

" - " , -
.
, , . ,
,
.
(Erich Gamma), , ( ).
, ,
, ,
.
. , . ,
, , , .

, ,
. ,
. , 2, ,
.

3.1.4.
, ,
-, , . , Ajax-, 2.11. ,
sendRequest(), . XMLHttpRequest initHttpRequest (),
onReadyState (). XMLHttpRequest ,
. ,
, ,
.
, 2.11, ,
. ,- , , , , .
-, onReadyState ().

104

I. Web-

.
, .
, , ,
, .
-

. JavaScript
. ContentLoader, . ? ,
URL , .
,
.
, . :
var loader=new net.ContentLoader('mydata.xml', parseMyData);
parseMyData ,
. ContentLoader 3.1.
, .
3.1. ContentLoader
//1
var net=new Object();
net.READY_STATE_UNINITIALIZED=O;
net.READY_STATE_LOADING=1 ;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;
// 2
net.ContentLoader=function(url,onload,onerror){
this.url=url;
this.req=null ;
this.onload=onload;
this.onerror=(onerror) ? onerror : this.defaultError;
this.loadXMLDoc(url) ;
}
net.ContentLoader.prototype={
// 3 initXMLHttpRequest
loadXMLDoc:function(url){
// 4 loadXML
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest() ;
} else if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.reqH
try{
var loader=this;
this.req.onreadystatechange=function(){
loader.onReadyState.call(loader);
}

3. /

105

// 5 sendRequest
this.req.open('GET, url, true);
this.req.send(null);
}catch (err){
this.onerror.call(this) ;
}
}

},

// 6
onReadyState:function(){
var req=this.req;
var ready=req.readyState;
if (ready==net.READY_STATE_COMPLETE){
var httpStatus=req.status;
if (httpStatus==200 || httpStatus==O){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
},
defaultError:function(){
alert("error fetching data!"
+"\n\nreadyState:"+this.req.readyState
+"\nstatus: "+this.req.status
+"\nheaders: "+this .req.getAHResponseHeaders ()) ;
}
}

net 1, .
, , , .
2,
, . , null,

.

, . JavaScript .
.
initXMLHttpRequest () 4
sendRequest () 5 .
. , initXMLHttpRequest()
sendRequest (), loadXMLDoc 3.
XMLHttpRequest ,
, ,
. , onReadyState () 6,

106

I. Web-

, 2.11.
onload onerror.
,
. onload onerror
Function, a F u n c t i o n . c a l l ( ) .
, Function. c a l l (), ,
t h i s .
, ContentLoader, . ContentLoader, XMLHttpRequest u r l , t h i s . :
function myCallBacM ) {
alert(
this.url
+" loaded! Here's the content:\n\n"
+this.req.responseText
);}
, , , , , JavaScript, , .

. "" , , . ,
,
. , , , .
.
, Ajax-, , , .
,
.

3.2.
,
Ajax, .
. ,
.
, , , , . .

3. Ajax

107

3.2.1- :
Fagade Adapter
Web-,
, , , ,
, ,
. Web , .
, ; , , , ,
.
JavaScript-
, , . .
DOM
2, Web- JavaScript DOM, HTML-. DOM
. , ,
. 3.2 ( , 3.5).
,
DOM- , .
3.2. getLeft (}
function getLeft(e){
if(!(e=xGetElementById(e))){
return 0;
}
var css=xDef(e.style);
if (ess && xStr(e.style.left)) {
iX=parselnt(e.style.left);
if(isNaN(iX)) iX=0;
}else if(ess && xDef(e.style.pixelLeft)) {
iX=e.style.pixelLeft;
}
return iX;
}

, DOM. CSS2, W3C,


s t y l e . l e f t . ,

108

I. Web-

, .
, . s t y l e . p i x e l L e f t , , ; ,
. Microsoft Internet Explorer. getLef t (), , , CSS, , ,
W3C. , , . , ,
, 2.
, , ,
,
. , . DOM
Ajax-.

2. Web- XMLHttpRequest,
.
XML- , ,
.
Internet Explorer ,
ActiveX, Mozilla Safari
. "" , XML-.
XMLHttpRequest, , .
, , ,
ActiveX . , ,
net.ContentLoader().
Facade
g e t L e f t ( ) , new net.ContentLoader() , , , . , ,
. (don't repeat yourself DRY). ,
, , , , ,
DOM .

3. Ajax

109

. 3.1. Facade,
X M L H t t p R e q u e s t
. l o a d X M L ()
X M L H t t p R e q u e s t "" .
,

, , Facade, , . ,
XMLHttpRequest ,
"" , (. 3.1).
.
, ,
CSS , , .
. getLeft (), 3.2,
, . ,
Fagade.
Adapter
Fagade Adapter.
, .
XMLHttpRequest Microsoft Mozilla.

I. Web-

Fagade ,
,
API, . , ,
[ Adapter. Sarissa, 3-5.1, Adapter ActiveX
Internet Explorer.
xMLHttpRequest, Mozilla.

( ) Ajax.
, JavaScript.

3.2.2. :
Observer
Ajax-,
. JavaScript , , Ajax, .
,
, .

,
. .

JavaScript- window, onload, ,
(, , DOM ).
, DOM,
, . JavaScript-,
, DOM.
window.onload.
window.onload=function(){
displayDiv=document.getElementById('display') ;
)

. , ( 13). , ,
DOM.
window.onload.
window.onload=function(){
feedDiv=document.getEleraentById('feeds') ;
}

3. Ajax

111

,
. window, onload , .
, onload.

. , .
window.onload=function() {
displayDiv=document.getElementById('display' ) ;
feedDiv=document.getElementById('feeds') ;
}

,
; .
, , DOM,
. , .. , : , .

.
window.onload=function(){
getDisplayElements();
getFeedElements();
}
function getDisplayElements(){
displayDiv=document.getElementById('display' ) ;
}
function getFeedElements(){
feedDiv=document.getElementByld('feeds' ) ;
}
: window.onload()
,
.
. , .
Observer
:
? window DOM.
, .
.

112

I. Web-

, , , .
, .
, onload. :
window.onloadListeners=new Array();
window.addOnLoadListener(listener){
window.onloadListeners[window.onloadListeners.length]=listener;
}
window
.
window.onload=function(){
for(var i=0;i<window.onloadListeners.length;i++){
var func=window.onlloadListeners[i] ;
func.callO ;
}
}
, , . ,
window. onload,
. , ""
, , .
, W3C . - , JavaScript.
4.
, Observer.
Observable ( ) Observer Listener,
Observable (. 3.2).
Observer . .
. , .
4, JavaScript.
, .
,
.

3. Ajax

113

. 3.2.
Observer. Observer,
,
Observable .

3.2.3. :
Command
, , (
),
. , ,
.
,
, DOM, . HTML-.
.
:
function buttonOnclickHandler(event){
var data=new Array();
data[0]=6;
data[l]=data[0]/3;
data[2]=data[0]*data[1]+7;
var newRow=createTableRow(dataTable) ;
for (var i=0;Kdata.length;i++){
createTableCell(newRow,data[i]);
}
}

, dataTable createTableRow() createTableCell () DOM. ,


, -

114

I. Web-

, , .
:
buttonDiv.onclick=buttonOnclickHandler;


, Ajax. , , . , , , p o l l e r . XMLHttpRequest, onreadystatechange onload.
, , .
function buttonOnclickHandler(event){
var data=calculate();
showData(dataTable,data);
function ajaxOnloadHandler(){
var data=calculate();
showData(otherDataTable,data);
function calculate(){
var data=new Array();
data[0]=6;
data[l]=data[0]/3;
data[2]=data[0]*data[1]+7;
return data;
function showData(table,data){
var newRow=createTableRow(table);
for (var i=0;i<data.length;i++){
createTableCell(newRow,data[i]) ;
buttonDiv.onclick=buttonOnclickHandler;
poller.onload=ajaxOnloadHandler;
c a l c u l a t e () showData (), onclick onload .
- , . , .
Command. Command ,
. - Command
. JavaScript Command,
.

3. Ajax

115

. 3.3. Command
.
Command

Command , .
Command,
.
Command
undo (), .
Command , , , ,
, (. 3.3).
, .
, . -
<Delete>. undo()
undo (), . ..

116

I. Web-

, Command ,
,
. ,
. , . 1,1
Web-, , , Ajax.
Command , . -'
"", , !
. Command 5,
.

3.2.4. :
Singleton
, , , . , .

, Ajax- : , , .
, .
( )

. , ( ), , . ( ) , , .

JavaScript.
var MODE_RED=1;
var MODE_AMBER=2;
var MODE_GREEN=2;
function TradingMode(){
this.mode=MODE_RED;
}
,
, .
getMode () setMode ()

3. Ajax

117

. 3.4. Ajax- -
, : .
T r a d i n g M o d e .
-, .
T r a d i n g M o d e , ,

, (, , ),
.
, , ,
, . ,
,
: .
. .
.
, ,
TradingMode (. 3.4).
, -
TradingMode. ,
, , . , ,

I. Web-

118

.
, ,
(singleton). , - , JavaScript-.

Java
Java : , get- ( 3.3).
3.3. TradingMode Java
public class TradingMode{
private s t a t i c TradingMode instance=null;
public i n t mode;
private TradingMode(){
mode=MODE_RED;
}
public static TradingMode getlnstance(){
if (instance==null){
instance=new TradingMode();

return instance;
}
public void setMode(int mode){
}

i
}

Java p r i v a t e public. , .
new TradingMode().setMode(MODE_AMBER);

,
:
TradingMode.getlnstance().setMode(MODE_AMBER);

, TradingMode
.
, JavaScript, , ,
.

JavaScript
JavaScript , , ,
"" , . JavaScript
, Function ( ).
TradingMode .

3. Ajax

119

function TradingMode(){
this.mode=MODE_RED;
}
TradingMode.prototype.setMode=function(){
}

.
TradingMode.instance=new TradingMode();
.
, , .
var TradingMode=new Object();
TradingMode.mode=MODE_RED;
TradingMode.setMode=function(){
}

.
var TradingMode={
mode:MODE_RED,
setMode:function() {
}
};

. , Java # .
, Prototype , .
.
iFrame,
. , , ( JavaScript
top ). , 3.4.
3.4. TradingMode JavaScript
Function getTradingMode(){
if (!top.TradingMode){
top.TradingMode=new Object();
top.TradingMode.mode=MODE_RED;
top.TradingMode.setMode=function(){
}

return top.TradingMode;
}

I Frame,
. ( ,

120

I. Web-

top.opener. -
.)
. - JavaScript.
Web- , -,
, Ajax .
, , . ,
, , ,
, ,
.
.
,
, ,
.

3.3. "-- "


, , .
, , , .
, Ajax-, .
"--" (Model-View-Controller MVC) , , ,
. , , Ajax-. 4 JavaScript-.
"--" ,
.
, . , ,
.
( ) , :
, , , . . ,
, .

3. Ajax

121

. 3.5.
"-".

.
.
,

MVC ,
.
, . , . ,
. ,
(. 3.5).
, ;
. , ,
, ,
, .
.
, , , , . ,
,
.
, . .
- , , .
, . ,
, -

122

i. Web-

, . , MVC
, , ,
, .
Web- MVC.
,
. Ajax , , . , Ajax- "--".
, MVC , , Ajax.
Web-,
, Ajax-.
Web-, , ORM (Object-Relational Mapping), Struts, Spring Tapestry, , , , .
4,
.

3.4.
"--" Web-, , . Web- , . , Web MVC
Web-, ?
, . , , , ,
.
"--"
HTML-, . Ajax, JavaScript-, , XML-,
HTTP-. -, .

3. Ajax

123

; 3.6. ,
.
XML. ,
., ,
XML-

3.4.1 Ajax,

, ,
Ajax.
Ajax 2 3.1.4, ,
4.
, Web-. ,
,
MVC , . .
,
.
,
, , . , , ,
, . . 3.6 , : , ,
, XML- , Ajax- ( ).
,
, .
;
, Category Garments.
SQL-, Menswear,
:
SELECT * FROM garments WHERE CATEGORY = 'Menswear';

, Ajax XML. , .

124

I. Web-

XML-
3.5 , .
.
MySQL,
. , ASP-, JSP-, Ruby.
3.5. , XML-
<?php
// ,
// XML-
header("Content-type: application/xml");
echo "<?xml version=\"l.0\" encoding=\"UTF-8\" ?>\n";
$db=mysql_connect("my_db_server","mysql_user") ;
//
mysql_select_db("mydb",$db);
$sql="SELECT id,title,description,price,colors,sizes"
."FROM garments WHERE category=\"{$cat}\"";
$result=mysql_query($sql,$db);
echo "<garments>\n";
//
while ($myrow = raysql_fetch_row($result)) {
printf("<garment id=\"%s\" title=\"%s\">\n"
."<description>%s</description>\n<price>%s</price>\n",
$myrow["id"],
$myrow["title"],
$myrow["description"],
$myrow["price"]);
if (!is_null($myrow["colors"])){
echo "<colors>{$myrow['colors']}</colors>\n";
}
if (!is_null($myrow["sizes"])){
echo "<sizes>{$myrow['sizes']}</sizes>\n";
}
echo "</garment>\n";
}
echo "</garments>\n";
?>

3.5 XML-. , ,
3.6. ,
. XML , , 2
XML-, XMLHttpRequest. 5
.
3.6. , 3.5
<garments>
<garment id="SCK001" t i t l e = " G o l f e r s ' Socks">
<description>Garish diamond patterned socks. Real wool.

3. Ajax

125

Real i t c h y . < / d e s c r i p t i o n >


<price>$5.99</price>
< c o l o r s > h e a t h e r combo,hawaiian medley,wild t u r k e y < / c o l o r s >
</garment>
< g a r m e n t id="HAT056" t i t l e = " D e e r s t a l k e r Cap">
<description>Complete with big flappy b i t s .
A s worn b y t h e g r e a t d e t e c t i v e S h e r l o c k H o l m e s .
Pipe is model's own.</description>
<price>$79.99</price>
< s i z e s > S , M, L, XL, e g g h e a d < / s i z e s >
</garment>
</garments>

, Web-. ,
Ajax- XML-.
. ,
(, Smart, Casual, Outdoor). , .
, XML- .

?

, , . -, "" SQL- .
, -.
.
. :
$sql="SELECT i d , t i t l e , d e s c r i p t i o n , p r i c e , c o l o r s , s i z e s "
."FROM garments WHERE ".$sqlWhere;
WHERE CGI, :
garments.php?sqlWhere=CATEGORY="Menswear"
, SQL-.

, .
-, "" XML ( p r i n t f echo).
. , , , ,
.

126

I. Web-

. .7. " ", .


C o l o r s ,

G a r m e n t s

-, XML- , .
, ,
, .
XML-. while
, . , , "" .

3.4.2.

, , Garments.
, , . " " . 3.7.
, ,
, .
garment_id Garments_to_Colors. Colors, ,
shocking pink blueberry,
b a t t l e s h i p gray . Garments_to_Colors, ,
.

3. Ajax

127

, , , .
, , ,
, .

Object-Relational Mapping
, .
ORM (Object-Relational Mapping),
, , , .
SQL-. , , PEAR DB_DataObject, EZPDO (Easy PHP Data Objects) Metastorage. ,
Java, . Hibernate (
.NET). ORM ,
.
MVC, ,
ORM
. XML-, Garment,
ORM . API
. 3.7 ,
ORM.
- (.. ) ,
Pear: :DB_DataObject, DB_DataObject. ORM -, , , SQL-.
3.7.
require_once "DB/DataObject.php";
class GarmentColor extends DB_DataObject {
var $id;
var $garment_id;
var $color_id;
}
class Color extends DB_DataObject {
var $id;
var $name;
}
class Garment extends DB_DataObject {
var $id;
var $title;
var $description;
var $price;
var $colors;

128

I. Web-
var $category;
function getColors(){
if (!isset($this->colors)){
$linkObject=new GarmentColor();
$linkObject->garment_id = $this->id;
$linkObject->find();
$colors=array();
while ($linkObject->fetch()){
$colorObject=new Color(),
$colorObject->id=$linkObject->color_id;
$colorObject->find();
while ($colorObj ect->fetch()){
$colors[] = clone($colorObject);
}
}
}
return $colors;
}
}

Garment, Color Garment, . . " ",


getColors ().
. , .

. PHP-. 3.8
, ORM.
3.8. , ORM
<?php
header("Content-type: application/xml");
echo "<?xml version=\"l.0\" encoding=\"UTF-8\" ?>\n";
include "gannent_busines8_objects.inc"
$garment=new Garment;
$garment->category = $_GET["cat"];
$number_of_rows = $garment->find();
echo "<garments>\n";
while ( $garment->fetch()) {
printf("<garment id=\"%s\" title=\"%s\">\n"
. "<description>%s</descrJ^tion>\n<price>%s</price>\n",
$garment->id,
$garment->title,
$garment->description,
$garment->price
);
Scolors

3. Ajax

129

$garment->getColors();
if (count($colors)>0){
echo "<colors>\n";
for($i=0; $i<count($colors);$i++){
echo "<color>{$colors[$i]}</color>\n";
}
echo "</colors>\n";
}
echo "</garment>\n";
}
echo "</garments>\n";
?>

SQL-, Garment, , .
, . XML . XML- .

3.4.3.
. , XML , . , ,
XML- , .
, , , . .

. , , , . . PHP, ASP JSP,
Web-. , ,
Java- CGI.
, , - .
, , PHP Smarty Apache Velocity ( Java;
.NET N Velocity), .

130

I. Web-

( if) (, for while). 3.9 PHP Smarty I


XML-.
<?xml version="1.0" encoding="UTF-8" ?>
<garments>
{section name=garment loop=$garments}
<garment id="{$garment.id}" title="{$garment.title}">
<description>{$garment.description}</description>
<price>{$garment.price}</price>
(if count($garment.getColors())>0}
<colors>
{section name=color loop=$garment.getColors()}
<color>$color->name</color>
{/section}
</colors>
{/if}
</garment>
{/section}
</garments>

garments, Garment.
, . ,
. XML-, , , ,
, 3.7. ,
.

XML-
Smarty.
. 3.10 , .

3.10. Smarty XML-


<?php
header("Content-type: application/xml");
include "garment_business_objects.inc";
include "smarty.class.php";
$garmentnew DataObjects_Garment;
$garment->category = $_GET["cat"] ;
$number_of_rows - $garment->find();
$smarty-new Smarty;
$3marty->assign('garments', $garments);
$smarty->display('garments_xml.tpl');
?>

3. Ajax

131

. 3.8. MVC
Web-. Web-


.
1 (),
,

. ,

.

,

. Smarty, .
, ,
. , ,
. display ()
.
,
. XML , . , : . , , XML.
Smarty , . ,
, .
, "-", , .
. 3.8.
ORM. , XML-. " " ,
.
"-" Web-. Ajax, XML-, ,
Web-, HTML-.
, , . Enterprise Jav-

132

I. Web-

aBeans, J2EE,
. .NET
, .
Struts (front controller),
. Apache Struts ,
.
. MVC
Web-.
"-"
Web ,
Ajax-. Ajax MVC
. 4
,
.
Ajax-.
, ,
.
Ajax , j
.

3.5.
.
.
, . ,
, . ,
, .
, .
. 4 5
ObjectViewer, 5 CommandQueue, 6 , 9 Stopwatch,
. 9 13
. ,
, .
, Ajax JavaScript, , ,
.

, Ajax-. -

3. Ajax

133

Ajax ,
,
.

3.5.1. ,

3.2.1, Ajax-. , , ( ,
Fagade). ,
.

, DHTML-. 2001 (Cross-Browser Extensions).
, DOM , ,
. Internet Explorer, 4,
Opera Mozilla.
;

. ,
document.getElementById(), ,
, , DOM. , , DOM . xGetElementByld() , DOM;

. DOM
, ,
setTimeout () .
DOM , , . :
xWidth(myElement)


DOM ( myElement , ).
,
.
xWidth(myElement,420)

134 I. Web-

,
, .
xWidth(secondElement,xWidth(firstElement))
,

Ajax-.

Sarissa
Sarissa JavaScript-
XML-. MSXML ActiveX- Internet
Explorer ( 3) Mozilla, Opera, Konqueror
Safari. , XPath XSLT,
.
Ajax- XMLHttpRequest .
Facade, Sarissa Adapter XMLHttpRequest , ( , Internet
Explorer). , , ,
ActiveX , 2, . , Sarissa
:
var xhr = new XMLHttpRequest();
xhr.open("GET", "myData.xml");
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
alert(xhr.responseXML);
}
}
xhr.send(null);
, 2.11, , API ,
Mozilla Safari, XMLHttpRequest.
, Sarissa XML-, , JavaScript XML. XML, . (
5.)

Prototype
Prototype
JavaScript. .

3. Ajax 135

.
Prototype ,
Java/C#, , , . Prototype .
Ajax- ,
Prototype, . .
Prototype. , Scriptaculous, Rico
Ruby on Rails.
Prototype "" .
. ,
Vehicle.
function Vehicle(numWheels,maxSpeed){
this.numWheels=numWheels;
this.maxSpeed=maxSpeed;
}
,
. , .
JavaScript, :
var passTrain=new Vehicle(24,100);
passTrain.carriageCount=12;
passTrain.addCarriage=function(){
this.carriageCount++;
}
passTrain.removeCarriage=function(){
this.carriageCount;
}
, ,
passTrain. , , . Prototype
,
. .
function CarriagePuller(carriageCount){
this.carriageCount=carriageCount;
this.addCarriage=function(){
this.carriageCount++;
)
this.removeCarriage=function(){
this.carriageCount;
}
}

136

I. Web-

, .
var parent=new Vehicle(24,100) ;
var extension=new CarriagePuller(12);
var passTrain=Object.extend(parent,extension);
, , . "-" ,
Vehicle CarriagePuller.
, , , ,
. ,
.
Prototype Ajax
, XMLHttpRequest . Ajax.Request
XMLHttpRequest.
var req=new Ajax.Request('myData.xml');

, Prototype. , .
, , . Ajax.Request
, , HTTP . Ajax.Request, , .
var req=new 1 Ajax.Request(
'myData.xml ,
{ method: 'get 1 ,
parameters: { name:'dave',likes:'chocolate,rhubarb' },
onLoaded: function(){ a l e r t ( ' l o a d e d ! ' ) ; },
onComplete: function(){
a l e r t (' done! \n\n' +req. transport. responseText) ;
}
}
);
. Prototype post, get . get
URL . post, . onLoaded
onComplete , , readyState XMLHttpRequest . req. t r a n s p o r t onComplete XMLHttpRequest.

3. Ajax

137

Ajax.Request Ajax.updater, , , .
, .
5.
,
. , , , , ,
. ,
, . , , , .

3.5.2.
. ,
DOM . , , , ,
, Swing, MFC Qt.
, Ajax. .
, ,
.
Scriptaculous
Scriptaculous Prototype,
.
Scriptaculous ,

.
Effects , DOM , . Effects
, . , Puff () , ,
. ,
P a r a l l e K ) , . Effects , .
6.
DOM , :
new Effect.SlideDown(myDOMElement);

138

I. Web-

, ,
.
, . , ,
.
. Scriptaculous
6 .
Scriptaculous , .
Sortable. DOM . , , , ,
(.. ,
, ,
).
Effect.
, .

Rico
Scriptaculous, Rico Prototype
. , Rico Behavior , DOM
. Behavior
Accordion, DOM
. (
outlook (outlook bar),
Microsoft Outlook.)
Rico Accordion. DOM; , , . div, div,
.
<div id='myAccordion'>
<div>
<div>Dictionary Definition</div>
<div>
<ul>
< l i > < b > n . < / b > A p o r t a b l e wind i n s t r u m e n t w i t h a s m a l l
k e y b o a r d a n d f r e e m e t a l r e e d s t h a t s o u n d when a i r i s
f o r c e d p a s t them b y p l e a t e d b e l l o w s o p e r a t e d b y t h e
player.</li>
<li><b>adj.</b>Having folds or bends l i k e t h e bellows
of an accordion: accordion p l e a t s ; accordion blinds.</li>

3. Ajax

139

</ul>
</div>
</div>
<div>
<div>A picture</div>
<div>
<img src='monkey-accordion.jpg'X/img>
</div>
</div>
</div>
, accordion (), , (. 3.9). .
div
Accordion, .
var outer=$('myAccordion') ;
outer.style.width='320px';
new Rico.Accordion{
outer,
{ panelHeight:400,
expandedBg:'#909090',
collapsedBg:'#404040',
}
);
. $ , , ,
Prototype. $ () DOM ,
xGetElementByld(), .
Accordion DOM,
( , Prototype).
Accordion.
, . . 3.9 , Accordion DOM.
Behavior "
, ,
.
JavaScript 4.
Rico,
Ajax. AjaxEngine. AjaxEngine XMLHttpRequest . XML, response. Rico

140

I. Web-

. 3.9. B e h a v i o r Rico DOM


. ,
B e h a v i o r .
A c c o r d i o n d i v ( ,
A c c o r d i o n , ).
( ),

. D0M, JavaScript.
5.5.3
.
, , .

3.5.3. ,
, , Web-
JavaScript-. ,
JavaScript- HTML.
.
, . ,
, 5.

DWR, JSON-RPC SAJAX


,
, . , , ,
. SAJAX ,
, , : ,

3. Ajax

141

python, Perl Ruby. DWR (Direct Web Remoting) Java . JSON-RPC


(JavaScript Object Notation-based Remote Procedure Calls) JavaScript , Python, Ruby, Perl Java.
, Ajax.
Ajax- ,
. , , , .
, , ,
, .
SAJAX -,
. ,
, .
<?php
function sayHello(name){
return("Hello! {$name} Ajax in A c t i o n ! ! ! ! " ) ;
?>
JavaScript-
, PHP-
SAJAX sajax_export.
<?php
require('Saj ax.php') ;
sajax_init() ;
sajax_export("sayHello") ;
?>

Web- SAJAX
JavaScript- .
JavaScript,
.
<script type='text/javascript'>
<?
sajax_show_javascript();
?>
alert(sayHello("Dave"));
</script>
sayHello ("Dave") JavaScript- Ajax- ,
HTTP-.
JavaScript. Ajax; SAJAX.

142

I. Web-


Ajax.
, ,

. 5.
, ,

, . Ajax, . Ajax-.

Backbase
Backbase Presentation Server ,
XML-.
HTML-, . Rico Behavior, , HTML- Backbase XHTML.
Backbase Java
.NET .

Echo2
NextApp Echo2 Java,
,
. ; JavaScript. , ,
, Ri.
Echo2 Ajax.
HTML, JavaScript CSS, , ,
.
Java. Echo2 . .

Ruby on Rails
Ruby on Rails ,
Ruby.

. "--" , 3.4. Ruby on Rails Web-, . -

3. Ajax

143

. , , .
Rails Ajax Prototype. Prototype Rails
, JavaScript- Prototype
Ruby . Echo2, Rails
Ajax-, JavaScript, ,
, Ajax.

Ajax. , .

,
Ajax
. .

3.6.
.
, XMLHttpRequest. ,
Ajax ,
.
, .
, .
Facade Adapter
. Ajax-
, . , . JavaScript.
Observer , . 4
. Command,
, Observer
. 5,
Command .
Singleton .
Ajax . 5.

144

I. Web-

"-", (
). , Web-.
, MVC , , .
.
, , , . ,
.
, . , Ajax-. ,
: , , , .
, , .
Ajax
, .
, Web-.

3.7.
(Martin Fowler), (Kent Beck),
(John Brant), (William Opdyke)
(Don Roberts) : Refactoring: Improving the Design of Existing Code (Addison-Wesley Professional, 1999).
(Erich Gamma), (Richard Helm), (Ralph Johnson) (John Vlissides), " ", Design Patterns (Addison-Wesley Professional, 1995), .

Eclipse ( ).
, Eclipse , http://www.artima.com/lejava/articles/gammadp.html.
(Michael Mahomoff) Web-, Ajax (http://www.ajaxpatterns.org).

II


, Ajax,
. , , , . 4
,
CSS, HTML JavaScript . 5
.

Web-




"--''
JavaScript-


"

148 II.

1 2 Ajax
, . 3 , .
, . , , , ,
Ajax, ,
.
, Ajax, , .
, "--", 3.
Observer . 5 .

4.1.
3 MVC , . , ,
, Web-,
.
MVC , . Ajax- . .

4.1.1. MVC

"--" Web . , , CGI-
..
MVC
. , , .
MVC .
, , , , . Ajax JavaScript.
( DOM),

4. Web-

149

, ,
.
,
, .
(, ),
.
. .
. ,
MVC . , , ,
, MVC.
. 4.1 MVC, , . , . .
-, .
, . , , ,
, . .
, MVC Web-. Web-.

4.1.2. MVC ,

.
JavaScript-, . MVC
.
-,
, , ,
-. . 4.2
MVC . MVC, , Ajax-,
Ajax .
"-" .
MVC (. 3), , Ajax

150

II.

. 4.1. "--"
, .
,
DOM.
JavaScript.

. 4.2. "--",
Ajax.
JavaScript-, -

4. Web-

151

. 4.3. MVC

. MVC ,
, . . 4.3 , MVC, ,
.
? MVC
JavaScript-, , . .

4.2. Ajax-
JavaScript-,
, ,
DOM, HTML .
DOM . 2.

152

II.

"--"
. -, , , . -,
. .
, , . Ajax- ,
.
.
- , ,
.
MVC ,
, , ""
, . ,
?
3 Web-,
CSS, HTML JavaScript . Web-, MVC.
, a HTML/DOM . " ", HTML
CSS . ,
. JavaScript- ,
. .

4.2.1.
JavaScript- , ( ) . , JavaScript.
<div class='importButton'
onclick= 1 importData("datafeed3.xml", raytextbox.value);'/>
, "" - . datafeed3? mytextbox. value?
importData () ? .
importData () -.
MVC, , . , div :

4. Web-

153

<div c l a s s = ' i m p o r t B u t t o n ' o n c l i c k = ' i m p o r t F e e d D a t a ( ) ' / >

, , ,
,
importFeedData().
function importFeedData(event){
importData("datafeed3.xml", mytextbox.value);
}
, DRY
(, "don't repeat yourself"
).
HTML-,
.
,
. , , . . ,
. HTML- :
<div class='importButton' id='dataFeedBtn'>
window, onload.
var dfBtn=document.getElementById('dataFeedBtn') ;
dfBtn.onclick=importFeedData;
,
, .
CSS.
CSS
, . 4.1 . .
4.1. musical.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN"
"http://www.w3.org/TR/xhtmll/DTD/xhtmll-strict.dtd">
<html> <head> <title>Keyboard</title> <link rel='stylesheet1
type='text/ess1 href='musical.css'/> <script
type='text/javascript' src='musical.js'X/script> <script
type='text/javascript'> window.onload=assignKeys; </script>
</head>
<body>
<div id='keyboard' class='musicalKeys'>
<! "" >
<div class='do musicalButton'X/div>

154 II.
<div class='re musicalButton'x/div>
<div class='mi musicalButton'X/div>
<div class='fa musicalButton'x/div>
<div class='so musicalButton'x/div>
<div class='la musicalButton'x/div>
<div class='ti musicalButton'x/div>
<div class='do musicalButton'x/div>
</div> <div id='console' class='console'> </div> </body>
</html>

DOCTYPE Strict ,
, . keyboard
, , , . , ,
, . musicalButton
, . musical.ess ( 4.2).
4.2. musical .ess
.body{
background-color: white;
} .musicalKeys{
background-color: #ffeOdO;
border: solid maroon 2px;
width: 536px;
height: 68px;
top: 24px;
left: 24px;
margin: 4px;
position: absolute;
overflow: auto;
} .musicalButton{
border: solid navy lpx;
width: 60px;
height: 60px;
position: relative;
margin: 2px;
float: left;
}
.do{ background-color: red; }
.re{ background-color: orange; }
.mi{ background-color: yellow; }
.fa{ background-color: green; }
.so{ background-color: blue; }
.la{ background-color: indigo; }
.ti{ background-color: violet;
} div.console{
font-family: arial, helvetica;
font-size: 16px;
color: navy;
background-color: white;
border: solid navy 2px;
width: 536px;

4. Web- 155
height: 320px;
top: 106px;
left: 24px;
margin: 4px;
position: absolute;
overflow: auto;
}

musicalButton , . . , ,
float.
, , .

JavaScript-, 4.3,
.
4.. musical, js
function assignKeys(){
// div
var keyboard=document.getElementById("keyboard");
//
var keys=keyboard.getEleraentsByTagName("div");
if (keys){
for(var i=0;i<keys.length;i++){
var key=keys[i];
var
classes=(key.className).split("
if (classes && classes.length>=2
SS
classes[1]=="musicalButton"){
var note=classes[0];
//
key.note=note;
key.onmouseover=playNote;
}

");

}
} function playNote(event){
//
var note=this.note;
var
console=document.getElementById("console") ;
if (note && console){
console.innerHTML+=note+" . ";
}
}

156

II.

assignKeys () window. onload.


( window.onload , .) keyboard
, getElementsByTagName ()
div. , div, ,
.
DOM, , className .
S t r i n g . s p l i t , , musicalButton.
, ,
DOM .
.
Web- , "" . . 4.4 .
. DIV, , , -
. , HTML , . . , . .
Rico (http://www.openrico.org/)
Behavior
DOM. Rico Accordion 3.5.2.
HTML
Behaviour (. ),
(Ben Nolan).
DOM , ,
CSS (. 2). assignKeys ()
keyboard,
div. ,
:
keyboard div

CSS, keyboard
. Behaviour.js
:
var myrules={ 'tkeyboard div 1 :
function(key){
var classes=(key.className).split(" " ) ;

4. Web-

157

. 4.4. " ",


.
.
"" ,

if (classes && classes.length>=2


&&
classes[l]=='musicalButton') {
var note=classes[0];
key.note=note;
key.onmouseover=playNote;
)
}
};

, CSS , ,
.
, , , .

4.2.2.
, , . HTML-

158 11.
. , HTML- .
div, .
,
, DOM
, , HTML-. , , . , ,
,
, . 4.4 JavaScript-,
.
4.4. musical_dyn_keys. js
var notes=new Array("do","re","mi","fa","so","la","ti","do");
function assignKeys(){
var candidates=document.getElementsByTagName("div");
if (candidates){
for(var i=O;i<candidates.length;i++){
var candidate=candidates[i];
if (candidate.className.indexOf('musicalKeys')>=0){
makeKeyboard(candidate);
,'
}
} function makeKeyboard(el){
for(var i=0;i<notes.length;i++){
var key=document.createElement("div");
key.className=notes[i]+" musicalButton";
key.note=notes[i];
key.onmouseover=playNote;
el.appendChild(key);
}
}
function playNote(event){
var note=this.note;
var console=document.getElementByld('console');
if (note && console){
console.innerHTML+note+" . ";
)

HTML-. JavaScript. assignKeys ()


div, , ,
className musicalKeys. , div, . makeKeyboard().
DOM, ,
DOM-, HTML-.
playNote () , .

4. Web- 159

div , , .
4.5.
4.5. muscal_dyn_keys .html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtmll/DTD/xhtmll-strict.dtd">
<html> <title>Two
Keyboards</title> <head> <link rel=*stylesheet 1
1
type-'text/ess
href-'musical_dyn_keys.ess'/>
<script
t y p e = ' t e x t / j a v a s c r i p t ' src=musical_dyn_keys.j s ' >
</script>
<script type='text/javascript'> window.onload=assignKeys;
</script>
</head>
<body> <div id='keyboard-top1 class='toplong
musicalKeys'X/div> <div id='keyboard-side1 class='sidebar
musicalKeys'X/div> <div id='console' class='console>
</div> </body> </html>

,
HTML- .
, , , musicalKeys . 4.6.
^ 4.6. musical_dyn_keys.css
/* */
.musicalKeys{
b a c k g r o u n d - c o l o r : #ffe0d0;
b o r d e r : s o l i d maroon 2px;
position: absolute;
overflow: a u t o ;
margin: 4px;
} /* */
.toplong{
width: 536;
height: 68;
top: 24;
left: 24;
} /* */
.sidebar{
width: 48px;
height: 400px;
top: 24px;
left: 570px;
}

160 II.

. 4.5.
. CSS ,
,
JavaScript-

musicalKeys , . toplong sidebar .


,
. JavaScript-; makeKeyboard(). . 4.5, , . ?
makeKeyboard ()
. ,

. , Java- LayoutManager, . ,
, , .
, , makeKey-j
board () . -!
;
f l o a t . , . .
. , , , -

4. Web-

161

, .
. . JavaScript-, .
. MVC Ajax- JavaScript- .

4.3. Ajax-
MVC
. , , Ajax,
. Web
, . , , , , W3C.
- , .
.

4.3.1. JavaScript-
JavaScript Web- , .
. , Ajax, ,
. , .. , -, .
JavaScript. DOM , . , , , myDomElement, :
myDomElement.onclick=showAnimatedMonkey
myDomElement DOM,
. showAnimatedMonkey ()
JavaScript, :

II.

162

4.1. ,
DOM

onmouseover

, ,

onmouseout

, ,

onmousemove

onclick

onkeypress

, ,
,

onfocus

onblur

f u n c t i o n showAnimatedMonkey(){
// }

,
, Function,
. .
myDomElement.onclick=showAnimatedMonkey();
, , .
DOM, ,
onclick , . ,
, ,
. ,
.
myDomElement.onclick=showAnimatedMonkey;
DOM, , . DOM , . , , . 4.1. XMLHttpRequest.onreadystate
window. onload .
,
, JavaScript. ,
Ajax.

4. Web-

163

, DOM , onclick. DOM. (..


, t h i s ) DOM,
( Function JavaScript ). , .
.
. , , . DOM, , .
,
. JavaScript. :
function Button(value,domEl){
this.domEl=domEl;
this.value=value;
this.domEl.onclick=this.clickHandler;
}
Button.
Button.prototype.clickHandler=function(){
alert(this.value);
}
,
, . , , undefined. . clickHandler () DOM,
DOM, JavaScript- Button. , t h i s . v a l u e
value DOM, Button.
, , ?
, :
function Button(value,domEl){
this.domEl=domEl;
this.value=value;
this.domEl.buttonObj =this ;
this.domEl.onclick=this.clickHandler;
}
DOM - value, Button, .
, .
Button.prototype.clickHandler=function(){
var buttonObj=this.buttonObj;
var value=(buttonObj && buttonObj.value) ?
buttonObj.value : "unknown value";
alert(value);
}

164 II.

DOM Button,
value, . DOM, ,
,
. , "" MVC, DOM,
, , .
.
, . Observer 3 , Observable Observer. , Ajax
. 4.3.3,
.

4.3.2. W3C
, W3C, , . DOM .
, , . "" (swallowing) . :
(.. , , ,
), , .
-.
Mozilla Safari , , addEventList e n e r ( ) , removeEventList e n e r ( ) . Internet Explorer
attachEvent () detachEvent (). xEvent,
(Mike Foster) ,
,
. Fagade (. 3).
,
. Mozilla,
,
DOM, . Internet Explorer Window, ,
DOM .
, xEvent.

4. Web-

165

, ,
.
.
,
, .

4.3.3. JavaScript
-
. 3 Observer, Observer .
. ,
W3C , ,
, , .
Observer, , .

,
, . 4.7
, div
, .
4.7. mousemat.html
<html> <head> <link rel='stylesheet'
type='text/ess' href='mousemat.ess 1 /> <script
type='text/javascript'> var cursor=null;
window.onload=function(){
var mat=document.getElementById('mousemat') ;
mat.onmousemove=mouseObserver;
cursor=document.getElementByld('cursor' ); }
function mouseObserver(event){
var e=event || window.event;
writeStatus(e);
drawThumbnail(e);
}
function writeStatus(e){
window.status=e.clientX+","+e.clientY;
}
function drawThumbnail(e){
cursor.style.left=((e.clientX/5)-2)+"px";
cursor.style.top=((e.clientY/5)-2)+"px";
} </script> </head> <body> <div class='mousemat1
id='mousemat'X/div> <div class='thumbnail'

166 11.

. 4.6. Mousemat ,
, : -,
, -, ,

id='thumbnail'>
<div class='cursor'
i d = ' c u r s o r ' / > </div>
</body>
</html>

-, ,
w r i t e s t a t u s ( ) . -, , , . drawThumbnail ( ) . Web- . 4.6.
,
, .

4. Web-

167

mouseObserver (). (
- .
Mozilla, Opera Safari, Internet Explorer
, Event window.event.)
w r i t e s t a t u s ()
drawThumbnail ( ) . , ,

, mouseObserver () .
,
.
Observer JavaScript-
-,
, ,
-.
:
window.onload=function() {
var mat=document.getElementById('mousemat') ;
var mouseRouter=new jsEvent.EventRouter(mat,"onmousemove");
mouseRouter.addListener(writeStatus) ;
mouseRouter.addListener(drawThumbnail);

}
EventRouter DOM , . - -. removeListener(),
.
, ?
. JavaScript
. ( , JavaScript.
, .)
j sEvent.EventRouter=function(el,eventType){
this.lsnrs=new Array();:
this.el=el;
el.eventRouter=this ;
el[eventType]=j sEvent.EventRouter.callback;
}
-;
. DOM
. , 3.5.1.

EventRouter callback. , JavaScript

. ,

168 II.
el.onmouseover
el['onmouseover']

, .
Java .NET.
.
j sEvent.EventRouter.callback=function(event){
var e=event || window.event;
var router=this.eventRouter;
router.notify(e)
}

,
D O M . EventRouter, D O M , , .
notify () , .
- 4.8.
4.8. EventRouter.js
var jsEvent=new Array();
j sEvent.EventRouter=function(el,eventType){
this.lsnrs=new Array();
this.el=el;
el.eventRouter=this;
el[eventType]=j sEvent.EventRouter.callback;
}
j sEvent.EventRouter.prototype.addListener=function(lsnr){
this.lsnrs.append(lsnr,true);
}
j sEvent.EventRouter.prototype.removeListener=function(lsnr){
this.lsnrs.remove(lsnr);
}
j sEvent.EventRouter.prototype.notify=function(e){
var lsnrs=this.lsnrs;
for(var i=O;i<lsnrs.length;i++){
var lsnr=lsnrs[i]; lsnr.call(this,e);
}
)
j sEvent.EventRouter.callback=function(event){
var e=event I| window.event;
var router=this.eventRouter;
router.notify(e)
)

, JavaScript, ,
. addListener() removeListener () , append () remove (). - Function, c a l l (), , (
) .

4. Web-

169

HTML- 4.9.
4.9. mousemat.html, EventRouter
<html> <head> 1 <link r e l = ' s t y l e s h e e t '
type='text/ess href='mousemat.ess' /> <script
type='text/javascript' s r c = ' e x t r a s - a r r a y . j s ' X / s c r i p t > <script
type='text/javascript' src='eventRouter.js'X/script> <script
var cursor=null;
t ype='text/javascript'>
window.onload=function(){
var mat=document.getElementById('mousemat');
cursor=document.getElementById('cursor' ) ;
var mouseRouter=new
jsEvent.EventRouter(mat,"onmousemove") ;
mouseRouter.addListener(writeStatus) ;
mouseRouter.addListener(drawThumbnail);
} function writeStatus(e){
window.status=e.clientX+","+e.clientY
} function drawThumbnail(e){
cursor.style.left-((e.clientX/5)-2)+"px";
cursor.style.top=((e.clientY/5)-2)+"px";
} </script> </head> <body> <div class='mousemat'
id='mousemat'x/div> <div class=' thumbnail'
id='thumbnail'>
<div class='cursor 1
id='cursor'/> </div> </body> </html>
JavaScript .
EventRouter,
. ,
. .
Ajax , , Observer, . MVC .

4.4. Ajax-
, . Document Object Model, DOM, Ajax. ,
JavaScript. , MVC
.

170

II.

JavaScript -- '
, , , .
, , . . , JavaScript ,
"--", -
, JavaScript, , Function . ,
JavaScript
, . , .

4.4.1. JavaScript

, DOM.
, , . JavaScript
. ,
, .
. 3 ,
. -;
, . , , .
, , .
.
. ,
. . 1.
JavaScript-, , . 4.10.
4.10. Garment, js
v a r garments=new A r r a y ( ) ; f u n c t i o n
Garment(id,title,description,price){
this.id=id;
garments[id]=this;
this.title=title;
this.description=description;
this.price=price;
this.colors=new Object();
this.sizes=new Object();
}
Garment.prototype.addColor(color){

4. Web-

171

this.colors.append(color,true); }
Garment.prototype.addSize(size){
this.sizes.append(size,true); )

.
( ,
, .
,
, .) ,
. ,
. , , . .
,
( ). .
get- set-
,
- .
( ),
.
XML-
Garment, .
, .
. JavaScript ; n u l l .
, .
var garment=new Garment(123);
var garment=new Garment(123,null,null,null);
, .

4.4.2.
Garment ,
XML-. 2, , 5,
. XML- , .
a t t r i b u t e s getNamedItem(), f i r s t C h i l d data. :
garment.description=descrTag.firstChild.data;
XML:

172

II.
<description>Large tweedy hat looking like an unappealing
strawberry </description>

, ;
. .
function unregisterGarment(id){
garments[id]null;
}
,
, ,
Garment. ,
Garment.
Garment.prototype.isValid=function(){
return garments[this.id]!=null;
}

, . , .
. . .
3.4.2 ORM (Object-Relational Mapping), .
, .
XML-
,
JavaScript-. . , ,
.
, , , JavaScript-, .
, .
Web- "" , , . . Aj -
, ,
. , , ,
, .. -
.
, , .. .

4. Web-

173

,
, , ,
.. ,
.
? 5, . .
,
.
.

4.5.
, , MVC, .
, . ,
(,
Enterprise JavaBeans, ).
, , .
DRY , .
,
MVC. .
, .
, .
, .

. Smalltalk Naked Objects Java/.NET. JavaScript
. , JavaScript, "Object Browser",
JavaScript.

4.5.1. JavaScript
,
.

174

II.

. 4.7. ObjectViewer
,
. ,

"", .
, . ,
: , , .. JavaScript- ObjectViewer, , ,
.
, . 4.7 ,
ObjectViewer.
, , .
. , , URL
. ObjectViewer ,
.
,
(reflection). , Java
.NET, . , JavaScript, .
, JavaScript ,
.
.
var description"";
for (var i in MyObj){
var property=MyObj[i];
description+=i+" = "+property+"(BBSS)n";
} alert(description);
,
, , .
, . 4.11
ObjectViewer.

4. Web-

175

4.11. ObjectViewer
objviewer.ObjectViewer=function(obj,div,isInline,addNew){
styling.removeAllChildren(div);
this.obj ect=obj;
this.mainDiv=div;
this.mainDiv.viewer=this ;
this.islnline=islnline;
this.addNew=addNew;
var table=document.createElement("table");
this.tbod=document.createElement("tbody");
table.appendChild(this.tbod);
this.fields=new ArrayO;
this.children=new ArrayO;
for (var i in this.object){
this.fields[i]=new objviewer.PropertyViewer(
this, i
);
}
objviewer.PropertyViewer=function(obj ectViewer,name){
this.objectViewer=objectViewer;
this.name=name;
this.value=objectViewer.object[this.name] ;
this.rowTr=document.createElement("tr") ;
this.rowTr.className='objViewRow' ;
this.valTd=document.createElement("td");
this.valTd.className='objViewValue' ;
this.valTd.viewer=this;
this.rowTr.appendChild(this.valTd) ;
var valDiv=this.renderSimple();
this.valTd.appendChild(valDiv);
viewer.tbod.appendChild(this.rowTr);
}
objviewer.PropertyViewer.prototype.renderSimple=function()
{
var valDiv=document.createElement("div");
var valTxt=document.createTextNode(this.value);
valDiv.appendChild(valTxt);
if (this.spec.editable){
valDiv.className+=" editable";
valDiv.viewer=this;
valDiv.onclick=objviewer.PropertyViewer.editSimpleProperty;
}
return valDiv;
}

: Obj ectViewer,
HTML-, PropertyViewer,

.
, . -, j ectViewer . , Obj ectViewer . D O M , , D O M . -

II.

176

.
, , .
, 4.12.
4.12. objviewspec
objviewer.ObjectViewer=function(obj,div,isInline,addNew){
styling.removeAllChildren(div) ;
this.object=obj;
this.spec=objviewer.getSpec(obj);
this.mainDiv=div;
this.mainDiv.viewer=this;
this.islnline=islnline;
this.addNew=addNew;
var table=document.createElement("table");
this.tbod=document.createElement("tbody") ;
table.appendChiId(this.tbod);
this. fields=new Array ();
this.children=new Array();
for (var i=0,-i<this.spec.length;i++){
this.fields[i]=new objviewer.PropertyViewer(
this,this.specfi]
);
}
objviewer.getSpec=function (obj){
return (obj.objViewSpec) ?
obj.objViewSpec :
objviewer.autoSpec(obj) ;
} objviewer.autoSpec=function(obj){
var members=new Array();
for (var propName in obj){
var spec={name:propName};
members.append(spec);
}
return members;
}
obj viewer.PropertyViewer=function(obj ectViewer,memberSpec) {
this.objectViewer=objectViewer;
this.spec=memberSpec;
this.name=this.spec.name;
}

objViewSpec, Objectviewer. ,
autoSpecO . objViewSpec , .
name. PropertyViewer , .
, Objectviewer,
.

4. Web-

177

, ObjectViewer,
, . , t o S t r i n g ().

[Object o b j e c t ] . Function
. .
instanceof. , , .

4.5.2.
, ObjectViewer. .
, .
,
type .
objviewer.TYPE_SIMPLE="simple";:
objviewer.TYPE_ARRAY="array"; objviewer.TYPE_FUNCTION="function";
obj viewer.TYPE_IMAGE_URL="image ur1" ;
objviewer.TYPE_OBJECT="object";

, ,
, 4.13.
4.13. autoSpec()
objviewer.autoSpec=function(obj){
var members=new Array();
for (var propName in obj){
var propValue=obj[name];
var propType=objviewer.autoType(value);
var spec={name:propName,type:propType};
members.append(spec);
}
if (obj && obj.length>0){
for(var i=0;i<obj.length;i++){
var propName="array ["+!+"]";
var propValue=obj[i];
var propType=objviewer.ObjectViewer.autoType(value);
var spec={name:propName,type:propType};
members.append(spec);
)
1
return members;
}

objviewer.autoType=function(value){
var type=objviewer.TYPE_SIMPLE;
if ((value instanceof Array)){

II.

178

type=objviewer.TYPE_ARRAY;
Jelse if (value instanceof Function){
type=objviewer.TYPE_FUNCTION;
}else if (value instanceof Object){
type=objviewer.TYPE_OBJECT;
}
return type;
}

,
, for... in.
PropertyViewer ,
. PropertyViewer 4.14.
4.14. PropertyViewer
objviewer.PropertyViewer=function
(objectViewer,memberSpec,appendAtTop){
this.objectViewer=objectViewer;
this.spec=memberSpec;
*
this.name=this.spec.name;
this.type=this.spec.type;
this.value=objectViewer.object[this.name];
this.rowTr=document.createElement("tr") ;
this.rowTr.className='objViewRow' ;
var isComplexType=(this.type==objviewer.TYPE_ARRAY
I| this.type==objviewer.TYPE_OBJECT);
if ( !(isComplexType &&
this.objectViewer.isInline )
this.nameTd=this.renderSideHeader() ;
this.rowTr.appendChild(this.nameTd);
this.valTd=document.createElement("td") ;
this.valTd.className='obj ViewValue ;
this.valTd.viewer=this;
this.rowTr.appendChild(this.valTd) ;
if (isComplexType){
if (this.viewer.islnline){
this.valTd.colSpan=2 ;
var nameDiv=this.renderTopHeader();
this.valTd.appendChild(nameDiv);
var valDiv=this.renderInlineObject();
this.valTd.appendChild(valDiv);
}else{
var valDiv=this.renderPopoutObject();
this.valTd.appendChild(valDiv);
else if
(this.type==objviewer.TYPE_IMAGE_URL){
var vallmg=this.renderlmage();

4. Web-

179

this.valTd.appendChild(vallmg);
}
else if
(this.type==objviewer.TYPE_SIMPLE){
var valTxt=this.renderSimple();
this.valTd.appendChild(valTxt);
}
if (appendAtTop){
styling.insertAtTop(viewer.tbod,this.rowTr);
}else{
viewer.tbod.appendChild(this.rowTr);
}
}

, , . Objectviewer Web-,
.
, . ,
objViewSpec .
Planet, . 4.7, ':
this.objViewSpec=[
{name:"name",
{name:"distance",
editable:true},
{name:"diameter",
editable:true},
{name:"image",
{name:"facts",
i n l i n e : t r u e } ];

type:"simple"},
type:"simple",
type:"simple",
type:"image u r l " } ,
type:"array",
addNew:this.newFact,

JSON (JavaScript
object notation). , ( ). JSON .
,
. , addNew, i n l i n e editable?
,
, , .
.

180 II.
4.5.3.
,
, "" ..
, , . ObjectViewer.
, , . , , ,
, . 4.15 ,
.
4.15. renderSimple ()
objviewer.PropertyViewer.prototype.renderSimple=function(){
var valDiv=document.createElement("div");
// ,
var valTxt=document
. createTextNode(this.value);
valDiv.appendChild(valTxt);
// ,
//
if (this.spec.editable){
valDiv.className+=" editable";
valDiv.viewer=this;
valDiv.onclick=obj viewer.PropertyViewer.editSimpleProperty ;
}
return valDiv;
}
//
obj viewer.PropertyViewer.editSimpleProperty=function(e){
var viewer=this.viewer;
if (viewer){
viewer.edit();
}
}
obj viewer.PropertyViewer.prototype.edit=function(){
if (this.type=objviewer.TYPE_SIMPLE){
var editor=document.createElement("input") ;
editor.value=this.value;
document.body.appendChild(editor);
var td=this.valTd;
xLeft(editor,xLeft(td));
xTop(editor,xTop(td)) ;
xWidth(editor,xWidth(td));
xHeight(editor,xHeight(td));
//
td.replaceChild(editor,td.firstChild);
//

4. Web-

181

editor.onblur=objviewer.
PropertyViewer.editBlur;
editor.viewer=this;
editor.focus();
}
}
//
objviewer.PropertyViewer
.editBlur=function(e){
var viewer=this.viewer;
if (viewer){
viewer.coiranitEdit(this.value);
}
}
objviewer.PropertyViewer.prototype.commitEdit=function(value){
if (this.type==objviewer.TYPE_SIMPLE){
this.value=value;
var valDiv=this.renderSimple();
var td=this.valTd;
td.replaceChild(valDiv,td.firstChild);
//
this.obj ectViewer
.notifyChange(this);
}
}

.
onclick DOM, . , ,
.
CSS , , . , , .
editSimpleProperty() . DOM,
, PropertyViewer e d i t ( ) .
4.3.1.
, , , HTML- , .
. onblur , ,
, .
, ,
.
notifyChangeO Ob j ectViewer
, commitEdit ().
4.16.

4.16. ObjectViewer.notiyChange()
obj viewer.Obj ectViewer.prototype
.notifyChange=function(propViewer){
if (this.onchangeRouter){
this.onchangeRouter.notify(propViewer);
}
if (this.parentObjViewer){
this.parentObjViewer.notifyChange(propViewer) ;
}

} obj viewer.Obj e c t V i e w e r . p r o t o t y p e
.addChangeListener=function(lsnr){
if (!this.onchangeRouter){
this.onchangeRouter=new
j s E v e n t . E v e n t R o u t e r ( t h i s , "onchange");
}
this.onchangeRouter.addListener(lsnr);
} obj viewer.Obj e c t V i e w e r . p r o t o t y p e
.removeChangeListener=function(lsnr){
i f (this.onchangeRouter){
this.onchangeRouter.removeListener(lsnr) ;
}
}
, ,
,
Observer EventRouter, 4.3.3. EventRouter onblur ,
,
Obj ectViewer.
Obj ectViewer , onchange, EventRouter. jectViewer ( , ), onchange .
Obj ectViewer, ,
.
, .
, :
var topview=new objviewer.ObjectViewer
(planets.solarSystem,mainDiv);
topview.addChangeListener(testListener);
t e s t L i s t e n e r , :
function testListener(propviewer){
window.status=propviewer.name+" ["+propviewer.type+"J =
"+propviewer.value;
}

4. Web-

183

,
, .
Objectviewer
.

4
"--" ,
Web- , .
Ajax-,
. , .
, .
.
, ,
, .
, .
, Observer , . JavaScript.
, . 5.
, . Objectviewer, , ,
MVC. ,
.
.
.

4.7.
Behaviour, , h t t p : / / r i p c o r d . c o . n z / b e h a v i o u r / .
, http://www.cross-browser.com.
Naked Objects ( h t t p : / /

184 II.

www.nakedobjects.org/). (Richard Pawson)


(Robert Matthews) Naked Objects (John Wiley <fe Sons, 2002)
, ,
"-".
,
Object Viewer, Jim's Cool Icons (http://snaught.com/
jimsCoolicons/) , Web-,
POV-Ray, , NASA.


Ajax-

. . .

Ajax-
,



HTTP-

186 11.

, 4.
,
. 4 ,
, ,
.
, , , , . , , Java,
. , , , , .
Web-,
, Ajax.
, , . 2 XMLHttpRequest
.

, XML-
DOM. ,
. ,
.
, Ajax-.

5.1. ,
Ajax- , . , . , , , , .html, .ess . j s .
. , . .
, ,
5.3.
, .. . HTTP ,
. .
4 , Ajax- (
), ( , ,
). , -

5. Ajax-

187

. 5.5; , , 3.
, ,
. ? ?
? , , . . Web-
, Ajax.

5.2.
Web- ,
, .
. , ,
, . ,
.
, , .

5.2.1.
,
, .
,
.
PHP, Java ASP;
ASP.NET Ruby. , , . Ajax , , .
, Ajax , .
Ajax- .
,
Ajax-, , .
. Web- ,
Ajax- ,
. ,
Web-.

188

II.

5.2.2. N-
,
, (tier). ,
, , ,
.
MVC. ,
, .

.
. , .
.
Web , Web. ,
.
Web-
. "/" , Web-
. -.
,
.
Web- . - .
- .
.
Ajax .
,
(. 5.1). ,
. JavaScript
.
,
. , . , .

5. Ajax-

Web-

Web-

189

. 5.1. Ajax-
.

5.2.3.

Ajax -
, " "
. , , "",
.
.
. ,
. Web- J2EE,
- . -. , Web-, . J2EE
(transfer objects), ,
.
.
Ajax . J2EE
. , . Ajax , , . '
JavaScript, ,
JavaScript-.
: .
5.3-5.5. ,
, . , ,
, Ajax.

190 II.

( ) Java
60 ( , , ).
, ,
, . .

5.3.
, , Ajax-.
, , .
HTML, JavaScript-, , ,
, - . , : . Aj-
. ,
, , , ,
.
Web-
. Web- , , -. Web , ,
.
,
. , , . ]
, Ajax-.

5.3.1. ,

.
. ,
.
Web- .
-
. . , , . 5.2.

5. Ajax-

191

Web-


. 5.2. Web-, .
, CGI-
.
,

Ajax- ,
, . ,
. , JavaScript-, .
HTML-, , XML .
Web-
,
. , ,
. Web- ,
. , , ,
,
, .
Ajax- , , , ,
. XML- , , -

192 II.
Web-

/
Web-


. 5.3. Model2.

.

, (, JSP-
-)

.

MVC. , , .

5.3.2. Model!
Model2 MVC.
, . Web ,
, . , Model2, Apache Struts.
Java . . 5.3 Web-,
Model2
, Ajax? Model2
,
.
, .

5. Ajax-

193

. , Model2,
, HTML XML
. ,
.
Model2 Web-
, .
.

5.3.3.
HTML- Web- HTML. ,
,
. ,
.
, ,
MFC, GTK+, Cocoa, Swing Qt.
Web
, , .
,
. , ,
. , , , .. Web HTML-
JavaScript-. ,
, . . 5.4
, .

, . , , Button , ,
valueChange ..
,

194

II.
Web-

. 5.4. , .
,
HTML- JavaScript-
"" , .

. "" ,
. , , ,
, , Model2.
, , ,
. , Windows Forms
.NET JSF (JavaServer Faces), .

5. Ajax-

195

Ajax-
Ajax?
, ,

. , Ajax-, , , Ajax. , JavaScript HTML-.
,
.
. Google Maps (. 1) , , . ,
, ,
, .

.
. ,
.
Ajax-,
.
, ""
, . Ajax-, ,
,
. ,
Ajax . CommandQueue,
5.5.3,
JSF , .
, .
,
Ajax.
Sun JSF ,
Ajax. ,
Ajax, .NET Forms;
Atlas. ( .)

196 II.

:
, Ajax?
, , -
.

5.3.4. ,
Web-
, SOA
(service-oriented architecture), .. ,
. ,
, .
, , Ajax.
Web-, a XML Ajax-.
Web- , . Web- , SOAP. Web-
, HTTP, , SOAP XML. XML-RPC, JSON-RPC
, ,
XMLHttpRequest, Web- .
Web- , Ajax , ,
, .
,
, . , .
, . , SOA Ajax
. , Ajax- .

,
Java, # , Web-.
Web-.
, , Microsoft Visual Studio Apache Axis for Java.
Ajax, DWR ( Java) SAJAX ( ,
.NET, Python ), , JavaScript.

5. Ajax-

197


. ,
.
, , Java DWR. .
package com.manning.aj axinaction;
public class Person{
private String name=null;
public Person(){
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}

JavaBeans.
, , ,
get- set-. DWR ,
JavaScript.
dwr.xml.
<dwr>
<init>
<convert id="person" converter="bean"
match="com.manning.aj axinaction.Person"/>
</init>
<allow>
<create creator="new" javascript="person">
<param name="class"
value="com.manning.aj axinaction.Person">
</create>
</allow>
</dwr>

i n i t
bean, allow ,
JavaScript- person. Person
, getName (), ,
Ajax :
var name=person.getName() ;

.
Person .
, , . . Person java.lang.Object ,
hashCode () t o s t r i n g ( ) . -

198 II.

. "" DWR.
JSONRPCBridge. registerObject (), , . , DWR , XML-. . , . 4
Obj ectviewer. .

Web
- , ?
, -, , java.lang.Object,
. , , , . ,
, . ,
,
. , . , DWR JSON-RPC,
Ajax. , Facade (. 5.5).
Facade . -, ,
. -,
, .
, , , , . ,
,
.
Facade , .

, . , . Ajax Web- ; ,
. , ,
,
, .
, ,
. . ( , ,

5. Ajax-

199

Web-
. 5.5. Ajax-
-,
Facade,
.
,

, , .)
, ,
, " ?".
. , ,
, , .
,
, , ,
. , , .
XML HTTP,
. , Ajax, ,
HTTP XML, .

200 II.

, , , -:
, . , ,
, , , , . Command,
3,
( ),
.
.
. , Ajax.
, .
Ajax . , .
Ajax . , , ,
.
, Ajax-. 4
,
XML 2. XML ,
. .

5.4. :
, Ajax.
,
. , , ,
, , . , . , . ,
, . ,

Ajax. ,
.
, Ajax, ,
, .
. : , , -

5. Ajax-

201

. ,
, ,
, .

5.4.1. ,

, , . ( , )
, .
, , , . , ,
,
. ,
, . , ,
( , , ),
( , , ). 4
, ,
.
.
;
.

5.4.2.
,
, . . .
; , , (. 5.6).
Objectviewer, 4, .
,
. , , ,
3. 5.1 .
.

202

II.

. 5.6. ,
,

5.1. popups .html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtmll/DTD/xhtmll-strict.dtd">
<html> <head> <title>Planet Browser</title>
<link rel=stylesheet type="text/css"
href="main.css"/>
<link rel=stylesheet type="text/css"
href="windows.ess"/>
<link rel=stylesheet type="text/css"
href="planets.css"/>
// JavaScript <script
type="text/javascript"
src="x/x_core. j s"x/script>
<script type="text/javascript"
src="x/x_event. j s"x/script>
<script type="text/javascript"
src="x/x_drag.j s"></script>
<script type="text/javascript"
src="windows. js"X/script>
<script type="text/javascript"
src="net.j s"></script>
<script type="text/javascript">
window.onload=function(){
var pbar=document.getElementByld("planets");
var children=pbar.getElementsByTagName("div");
for(var i=O;i<children.length;i++){

5. Ajax-

203

//

children[i].onclick=showlnfo;
}

</script>
</head> <body>
// 0 , <div
class="planetbar" id="planets">
<div class="planetbutton" id="mercury">
<img src="img/ball-mercury.gif"
alt="mercury"/> </div> <div class="planetbutton" id="venus">
<img src="img/ball-venus.gif" alt="venus"/>
</div> <div class="planetbutton" id="earth">
<img src="img/ball-earth.gif" alt="earth"/>
</div> <div class="planetbutton" id="mars">
<img src="img/ball-mars.gif" alt="mars"/>
</div> <div class="planetbutton" id="jupiter">
<img src="img/ball-jupiter.gif"
alt="jupiter"/> </div> <div class="planetbutton" id="saturn">
<img src="img/ball-saturn.gif" alt="saturn"/>
</div> <div class="planetbutton" id="uranus">
<img src="img/ball-uranus.gif" alt="uranus"/>
</div> <div class="planetbutton" id="neptune">
<img src="img/ball-neptune.gif"
alt="neptune"/> </div> <div class="planetbutton" id="pluto">
<img src="img/ball-pluto.gif" alt="pluto"/>
</div> </div>
</body> </html>

JavaScript- .
, n e t . j s , HTTP-, XMLHttpRequest, 2. windows, js ,
.
. ;
.
var MyWindow=new Window(bodyDiv,title,x,y, w,h);
bodyDiv DOM, ; t i t l e ,
, , , w h . DOM , .
Window Web-,
. HTML-, , div , window.onload

onclick. showlnf (), .


.
, , .

204

II.

. 5.7. Ajax-,
. I F r a m e
.
,
I F r a m e .

5.4.3. ,
Ajax ,
Web-.
; 1,
"". , -:
, ,
Ajax-.

, , HTML- !
IFrame, Web-. IFrame 2.
HTML-
. , . . 5.7
, .
5.2 . , .
5.2. ContentPopup. j s
var offset=8;
function showlnfo(event){
var planet=this.id;
var infoWin=new ContentPopup(
"info_"+planet+".html",
planet+"Popup",

5. Ajax- 205
planet,offset,offset,320,320
);
offset+=32;
}
function'
ContentPopup(url,winEl,displayStr,x,y,w,h){
var bod=document.createElement("div") ;
document.body.appendChild(bod);
this.iframe=document.createElement("iframe");
this.iframe.className="winContents";
this.iframe.src=url;
bod.appendChild(this.iframe);
this.win=new windows.Window(bod,displayStr,x,y,w,h);
}

showlnf () DOM, . t h i s
DOM. ,
, .
ContentPopup, Window, I Frame,
, , URL. HTML-
URL. , , , , URL .
, iFrame ( 5.3), .
5.3. info_earth.html
<html> <head>
<link rel=stylesheet type="text/css" href="../style.css"/>
</head>
<body class="info">
<div class="framedlnfo" id="info">
<div class="title" id="infotitle">earth</div>
<div class="content" id="infocontent">
A small blue planet near the outer rim of the galaxy,
third planet out from a middle-sized sun.
</div> </div> </body> </html>

:
HTML-, Web-.
, , - ,
IFrame URL, . ; .
, HTML-.

206

II.

: !
, , ,
, , . HTML
, , , .
, . Ajax , , ,
.
. , .

, ,
Web-, .
I Frame , . . ,
. I Frame , ,
,
.
,
IFrame. I Frame , , IFrame
, .
. , .
, Web-. -, . -,
, , IFrame
. , , , "" .
, , Ajax, " ".
, . , , . ,
, . . JavaScript-.

5. Ajax-

207

,
, , ,
, IFrame.
HTML-, , innerHTML DOM . 12.

5.4.4. ,
JavaScript- , ,
. JavaScript-, , , . .
.
, , Java .NET.
RMI, Jini, .NET Remoting Framework. Web- ! , Ajax
.

Web- HTML- JavaScript-
, Web-. Ajax,
Web- , ,
. , ,
. , , , .
. 5.8 , .
, , , " ", .
. , ,
, , .
, .

. API . . , , -

208

II.

. 5.8. Ajax-, .

JavaScript-. .
,

.
Fagade . , JavaScript- , , , ,
XML-. , , , .
. 5.4 API
.
5.4. showPopupO
var offset=8;
function showPopup(name,description) {
var win=new ScriptlframePopup
(name,description,offset,offset,320,320);
offset+=32;
}
function ScriptlframePopup(name,description,x,y,w,h){
var bod=document.createElement("div");
document.body.appendChild(bod);
this.contentDiv=document.createElement("div");
this.contentDiv.className="winContents";
this.contentDiv.innerHTML=description;
bod.appendChild(thi s.contentDiv);
this.win=new windows.Window(bod,name,x,y,w,h);
}

showPopup (),
. 5.5 , .

5. Ajax-

209

5.5. s c r i p t _ e a r t h . js
var name='earth'; var description="A small blue
planet near the outer rim of the galaxy,"
+"third planet out from a middle-sized sun.";
showPopup (name,description);
( ) . ,
. , . .
IFrame
JavaScript-, HTML- <script>,
. IFrame . showlnf () IFrame .
function showlnf(event){
var p l a n e t = t h i s . i d ;
var s c r i p t U r l = " s c r i p t _ " + p l a n e t + " . h t m l " ;
var
dataframe=document.getElementById('dataframe') ;
if
(!dataframe){
dataframe=document.createElement("iframe");
dataframe.className='dataframe' ;
dataframe.id='dataframe' ;
dataframe.src=scriptUrl;
document.body.appendChild(dataframe);
)else{ dataframe.src=scriptUrl;
}
}

DOM .
IFrame,
, . HTML-,
5.6.
5.6. s c r i p t e a r t h . h t m l
<html> <head> <script type='text/javascript'
s r c = ' s c r i p t _ e a r t h . j s ' > </script> </head> <body> </body>
</html>

, ,
IFrame JavaScript- API, . ,
showPopup () IFrame.
showPopup (name, description);

210 II.

, , top,
.
top.showPopup(name,description);
I Frame I Frame
, .
. I Frame , . , P l a n e t l n f o . js
Planetlnfo, :
var pinfo=new PlanetInfo(name,description);
, Planetlnfo. js IFrame, <script>.
<script type='text/javascript 1
src='Planetlnfo.j s'></script> <script
type='text/j avascript'>
var pinfo=new Planetlnfo(name,description);
</script>
Planetlnfo, I frame, ,
, , . IFrame,
, IFrame, . ,
instanceof (. 5.1).

, . , API .
:
function createPlanetlnfo(name,description){
return new Planetlnfo(name,description);
}

5. Ajax- 211


Planetlnfo.
<script type='text/javascript'>
var pinfo=createPlanetInfo(name,description);
</script>
showPopupO 5.4
ScriptlframePopup.
.
HTML-, , , ,
. JavaScript. , .
XMLHttpRequest eval()
, JavaScript eval (), JavaScript .
, eval ()
. , eval ()
. ,
, , XMLHttpRequest. eval ()
, .
eval (), :
function showlnfo(event){
var p l a n e t = t h i s . i d ;
var scriptUrl="script_"+planet+".js";
new net.ContentLoader(scriptUrl, evalScript); )
function evalScript(){
var script=this.req.responseText;
eval(script); }
showlnfoO XMLHttpRequest ( ContentLoader) ; HTML- . ,
e v a l S c r i p t ( ) , ;
ContentLoader. e v a l S c r i p t () , responseText, XMLHttpRequest.
IFrame, .
" ". , ; IFrame
eval ( ) . , , , .

212 II.



; ,
. ,
, , , .

. JavaScript-, ,
, Ajax-.
API .
, ,
. Ajax-
, . .

5.4.5. ,
, , , , ""
, .. .
, .

,
Ajax-, , , Java .NET, . JavaScript- ;
"" .
, ,
, JavaScript,
. , , . 5.9.
, ,
, . XML, .
XML-
XML . ,
Ajax- , , XMLHttpRequest, XML-. XMLHttpRequest application/xml text/xml, -

5. Ajax-

213

. 5.9. , ,
(,
, XML).
()

DOM (Document Object Model). 5.7


, , XML.
5.7. DataXMLPopup. js
var offset=8; function
showPopup(name,description){
var win=new DataPopup(name,description,offset,offset,320,320);
offset+=32;
}
function
DataPopup(name,description, x, y,w,h){
var bod=document.createElement("div");
document.body.appendChild(bod);
this.contentDiv=document.createElement("div");
this.contentDiv.className="winContents";
this.contentDiv.innerHTML=description;
bod.appendChild(this.contentDiv);
this.win=new windows.Window(bod,name,x,y,w,h);
}
function showlnfo(event){
var planet=this.id;
var scriptUrl=planet+".xml";
new net.ContentLoader(scriptUrl,parseXML);
}
function parseXML(){
var name="";
var descrip="";
var xmlDoc=this.req.responseXML;
var elDocRoot=xmlDoc.getElementsByTagName("planet")[0];
if (elDocRoot){
attrs=elDocRoot.attributes;

|p

214

II.
name=attrs.getNamedItem("name").value;
var ptype=attrs.getNamedItem("type").value;
if (ptype){
descrip+="<h2>"+ptype+"</h2>";
}
descrip+="<ul>";
for(var i=0;i<elDocRoot,childNodes.length;i++){
elChild=elDocRoot.childNodes[i];
if (elChild.nodeName=="info"){
descrip+="<li>"+elChild.firstChild.data+"</li>(BBSS)n";
}
}
descrip+="</ul>";
}else{
alert("no document");
}
top.showPopup(name,descrip);
}

showinfo() XMLHttpRequest, ContentLoader,


parseXML (). ,
e v a l S c r i p t ( ) , 5.6.3. , DOM,
showPopup. 5.8
, XML.
5.8. earth.xml
<planet name="earth" type="small">
<info id="a" author="dave" date="26/05/04">
Earth is a small planet, t h i r d from the sun
</info>
<info id="b" author="dave" date="27/02/05">
Surface coverage of water is roughly two-thirds
</info>
<info id="c" author="dave" date="03/05/05">
Exhibits a remarkable diversity of climates and landscapes
</info>
</planet>

XML , , , . , <info>,
parseXML () HTML-.

5. Ajax-

215

, XML
. , , , , . , ,
: JavaScript-.
, JSON.
.
JSON-
XMLHttpRequest . XML, . Ajax- JSON
(JavaScript Object Notation),
JavaScript. 5.9 , , ,
JSON.
5.9. DataJSONPopup. j s
function showlnfo(event)
{
var planet=this.id;
var scriptUrl=planet+".json";
new net.ContentLoader(scriptUrl,parseJSON);
}
function parseJSON()
{
var name="";
var descrip="";
var jsonTxt=net.req.responseText;
var jsonObj=eval("("+jsonTxt+")");
name=j sonObj.planet.name
var ptype=jsonObj.planet.type;
if (ptypeH
descrip+="<h2>"+ptype+"</h2>";
)
var infos=jsonObj.planet.info;
descrip+="<ul>";
for(var i in infos){
descrip+="<li>"+infos[i]+"</li>\n";
}
descrip+="</ul>";
top.showPopup(name,descrip);

-J

ContentLoader.
parse JSON (). JavaScript-,
eval ().

II.

216

var jsonObj=eval("("+jsonTxt+")") ;

,
. ,
, DOM,
XML. showPopup() , , 5.7.
JSON-? 5.10 , JSON.
5.10. e a r t h , json
{ "planet":
{
"name": "earth",
"type": "small",
"info":
[
"Earth is a small planet, third from the sun",
"Surface coverage of water is roughly two-thirds",
"Exhibits a remarkable diversity of climates and landscapes"
]
}

_J

,
. . planet, . name type , info .
JSON , XML, JSON-
JavaScript, Mozilla Rhino
Java Microsoft JScript .NET. JSON-RPC
JSON ( ), JavaScript "Stringiner", JavaScript JSON. , JSON
. JavaScript
, ,
JSON. JSON-RPC , JSON- , , .
" ".
, ,
XML, .

5. Ajax-

217

XSLT
DOM
flTML- ( 5.7.3) XSLT- XML XHTML. , , . , .
,
, , , , . XSLT-
11.

, , ,
, , . .
,
.
: Web- "" , . ,
.
,
. , .

5.5.

. ,
.
,
.
,
. : HTML-
XMLHttpRequest. .

218 II.

5.5.1. HTML-
Web- HTML- . HTML.
<form method="POST" action="myFormHandlerURL.php">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="login"/>
</form>
. dave
letmein submit, HTTP-
POST myFormHandlerURL.php. username=dave&password=letmein. Web . -
.
Web-
JavaScript-,
. ,
, .
<form id="myForm" method="POST" action=""
onsubmit="validateForm(); return false;">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="login"/>
</form>
, , :
function validateForm(){
var form=document.getElementById('myForm') ;
var user=form.elements[0].value;
var pwd=form.elements[1].value;
if (user && user.length>0 && pwd && pwd.length>0){
form.action='myFormHandlerURL.php';
form.submit();
}
else
{
a l e r t ( " p l e a s e f i l l i n your c r e d e n t i a l s b e f o r e logging i n " ) ;
}
}

action.
URL . JavaScript- , submit
- , ..
,

5. Ajax-

219

^ibi . 9 10
HTML-.

, .
,
. 5.11.
5.11. submitData()
function addParam(form,key,value)
{
var input=document.createElement("input");
input.name=key;
input.value=value;
form.appendChild(input);
}
function submitData(url,data)
{
var form=document.createElement("form");
form.action=ur1;
form.method="POST";
for (var i in data){
addParam(form,i,data[i]);
}
form.style.display="none";
document.body.appendChild(form);
form.submit();
_}
submitData () ,
addParam (). submitData () :
submitData(
"myFormHandlerURL.php",
{username:"dave",password:"letmein"}
);
, . iFrame, , .
XMLHttpRequest.

5.5.2. XMLHttpRequest
XMLHttpRequest , 2. . POST .

220

II.

5.12 ContentLoader, -
3.1. ,
HTTP-
5.12. ContentLoader
/ /
net.ContentLoader=function
(url,onload,onerror, method,params,contentType)
this.onload=onload;
this.onerror=(onerror) ? onerror :
this.defaultError;
this.loadXMLDoc(url,method,params,contentType); }
net.ContentLoader.prototype.loadXMLDoc
=function(ur1,method,params,contentType){
if (!method){
method="GET";
if (icontentType && method=="POST"){
contentType="application/x-www-form-urlencoded";
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
else
if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
if (this.req){
try{
this.req.onreadystatechange=net.ContentLoader.onReadyState;
// -
this.req.open( method,url,true);
//
if (contentType){
this.req.setRequestHeader("Content-Type", contentType);
//
this.req.send( params);
}catch (err){
this.onerror.call(this) ;
}
_

. ;

5. Ajax-

221

.
URL ( action
) onload. HTTP-, . , - POST application/x-www-f ormurlencoded. , . HTTP- open () XMLHttpRequest
send( ). , :
var loader=net.ContentLoader(
'myFormHandlerURL.php', showResponse, n u l l ,
' POST', 'username=dave&password=letmein'
);

, submitData(), 5.11. , , , , :
name=daveSjob=book&work=Ajax_In+Action
.
: , , ..
Objectviewer, 4, ,
.

5.5.3.
3 Objectviewer, , ,
. , ,
,
.
,
. ( Mozilla Firefox .
, JavaScript,
.)
.

222 II.

, updateDomainModel. jsp, .
,
.
.
, .
,
.
function updateServer(propviewer)
{
var planetObj=propviewer.viewer.object;
var planetId=planetObj.id;
var propName=propviewer.name;
var val=propviewer.value;
net.ContentLoader
(
'updateDomainModel.jsp', someResponseHandler,
n u l l , 'POST', 'planetId='+encodeURI(planetId)
+'&propertyName='+encodeURI(propName)
+'&value='+encodeURI(val)
);
}
ObjectViewer.
myObjectViewer.addChangeListener(updateServer) ;
,
, . ,
, , ,
, .
,
JavaScript, 5.13.
5.13. CommandQueue
/ /
net.CommandQueue=function(id, u r l , freq)
{
this.id=id;
net.cmdQueues[id]=this;
this.url=url;
this.queued=new Array();
this.sent=new Array();
if (freq)
{
this.repeat(freq);
}
}

5. Ajax- 223
// 0
net.CommandQueue.prototype.addCommand=function(command){
if (this.isCommand(command))
{
this.queue.append(command,true);
}
}
net.CommandQueue.prototype.fireRequest=function(){
if (this.queued.length==0)
{
return;
}
var data="data=";
for(var i=0; i<this.queued.length;i++){
var cmd=this.queuedfi];
if (this.isCommand(cmd)){
data+=cmd.toRequestString();
this.sent[cmd.id]=cmd;
}
}
this .queued=new ArrayO;
this.loader=new net.ContentLoader(
this.url, net.CommandQueue.onload,net.CommandQueue.onerro:
"POST",data
);
}
//
net.CommandQueue.prototype.isCommand=function(obj)
{
return
(
obj.implementsPropC'id")
&& obj.implementsFunc("toRequestString")
&& obj.implementsFunc("parseResponse")
);
}
//
net.CommandQueue.onload=function(loader)
{
var xmlDoc=net.req.responseXML;
var elDocRoot=xmlDoc.getElementsByTagName("commands")[0];
if (elDocRoot)
{
f o r ( i = 0 ; K e l D o c R o o t . c h i l d N o d e s . l e n g t h ; i++)
{
elChild=elDocRoot.childNodes[i];
if (elChild.nodeName=="command")

II.

224

{
var attrs=elChild.attributes;
var id=attrs.getNamedItem("id").value;
var command=net.commandQueue.sent[id];
if (command)
{
command.parseResponse(elChild);
}
}
}
}
}
net.CommandQueue.onerror=function(loader){
alert("problem sending the data to the server"); }
//
net.CommandQueue.prototype.repeat=function(freq){
this.unrepeat();
if (freq>0){
this.freq=freq;
var cmd="net.cmdQueues["+this.id+"].fireRequest()";
this.repeater=setlnterval(cmd,freq*1000) ;
}
}
// 0
net.CommandQueue.prototype.unrepeat=function()
{
if (this.repeater)
{
clearlnterval(this.repeater) ;
}
this.repeater=null;

CommandQueue ( ,
Command) , URL
, .
. , .
,
.
. queued
; .
sent . , , . Command, isCommand() . .

5. Ajax- 225

.

POST .
, .
implementsFunc(). Object, , JavaScript,
implements Func .
Obj ect.prototype.implementsFunc=function(funcName){
return this[funcName] && this[funcName] instanceof
Function; }
JavaScript . , . onload , XML-. <command>, <commands>.
repeat () unrepeat () .
Command, , , 5.14.
5.14. UpdatePropertyCommand
planets.commands.UpdatePropertyCommand=function(owner,field,value)
{
this.id=this.owner.id+"_"+field;
this.obj=owner;
this.field-field;
this.value=value;
}
planets.commands.UpdatePropertyCommand.toRequestString=
function()
{
return
{
type:"updateProperty",
id:this.id,
planetld:this.owner.id,
field:this.field,
value:this.value
}.simpleXmlif("command");
}

226 II.
planets.commands.UpdatePropertyCommand.parseResponse=
function(docEl)
{
var attrs=docEl.attributes;
var status=attrs.getNamedItem("status").value;
if (status!="ok")
{
var
reason=attrs.getNamedItem("message").value;
a l e r t ( " f a i l e d t o update "
+this.field+" to "+this.value
+ "\n\n"+reason);
}
}

, . toRequeststring()
XML-,
, Object.
Object.prototype.simpleXmlify=function(tagname){
var xml="<"+tagname;
for (i in t h i s ) {
if ( ! t h i s [ i ] instanceof Function)
{
xml+=" " + i + " = \ " " + t h i s [ i ] + " \ " " ;
}
}
xml+="/>";return xml;
)
XML- ( ).
<command type='update Property'
id='001_diameter'
planetld='mercury'
field='diameter'
value='3'
/>
, .
.
, .
POST, ,
,
.
, . onload, CommandQueue, , Command sent parseResponse ()
Command. :

5. Ajax- 227

<commands>
<command id='001_diameter' s t a t u s = ' o k ' / >
<command id='003_albedo'
s t a t u s = ' f a i l e d ' message='value out of range'/>
<command id='004_hairColor'
s t a t u s = ' f a i l e d ' message='invalid p r o p e r t y name'/>
< / cornmands >
, , . message. ( a l e r t ())
.
, ,
. HTTP-. Java-, , 5.15.
5.15. CommandServlet .Java
public class CommandServlet extends HttpServlet
{
private Map commandTypes=null;
public void i n i t ( ) throws ServletException
{
ServletConfig
config=getServletConfig();
//
commandTypes=new HashMap();
boolean more=true;
f o r ( i n t counter=l;more;counter++){
String typeName=config.getlnitParameter("type"+counter);
String typelmpl=config.getlnitParameter("impl"+counter);

i f (typeName==null | | typelmpl==null){
more=false;
}
else
{
try{
Class cls=Class.forName(typelmpl);
commandTypes.put(typeName,els);
}
catch (ClassNotFoundException clanfex)
{
this.log(
"couldn't resolve handler class name"+typelmpl);
}
}

228

II.
protected void doPost
(
HttpServletRequest req,
HttpServletResponse resp
)
throws IOException{
// 0
resp.setContentType("text/xml");
Reader reader=req.getReader();
Writer writer=resp.getWriter() ;
try{ SAXBuilder builder=new SAXBuilder(false);
// XML-
Document doc=builder.build(reader);
Element root=doc.getRootElement();
if

("commands".equals(root.getName())){
for(Iterator iter=root.getChildren("command").iterator();
iter.hasNext();)
{
Element el=(Element)(iter.next());
String type=el.getAttributeValue("type");
XMLCommandProcessor command=getCommand(type,writer);
if (command!=null)
{
//
Element result=command.processXML(el);
writer.write(result.toString());
}

}
}
else
{
sendError(writer,
"incorrect document format - "
+"expected top-level command tag");
}
}
catch (JDOMException jdomex){
sendError(writer,"unable to parse request document");
}
}
private XMLCommandProcessor getCommand
(String type,Writer writer)
throws IOException{
//
XMLCommandProcessor cmd=null;
Class cls=(Class)(commandTypes.get(type));
if (cls!=null){

5. Ajax-

229

try{ cmd=(XMLCommandProcessor)(els.newlnstance()) ;
}catch (ClassCastException castex){
sendError(writer,
"class "+cls.getName()
+" is not a command");
}
catch (InstantiationException instex)
{

sendError(writer,
"not able to create class "+cls.getName());
catch (IllegalAccessException illex)

{
sendError(writer,
"not allowed to create class "+cls.getName());
}
}else{
sendError(writer,"no command type registered for "+type);
}
return cmd;
}
private void sendError
(Writer w r i t e r , S t r i n g message) throws IOException{
w r i t e r . w r i t e ( " < e r r o r msg='"+message+" ' / > " ) ;
writer.flush();
}
_}

XMLCommandProcessor,
ServletConfig .

XML-. POST
XML- JDOM ,
<coramand>, XMLCommandProcessor .
, getCommand ()
, .
XMLCommandProcessor .
public interface XMLCommandProcessor {
Element processXML(Element e l ) ; }
, XML JDOM. Element
, . ,
,
5.16.

230

II.
5.16. PlanetUpdateCoimandProcessor. Java
public class PlanetUpdateCommandProcessor
implements XMLCommandProcessor
{
public Element processXML(Element el)
{
// XML-
Element result=new Element("command");
String id-el.getAttributeValue("id");
result.setAttribute("id", id);
String status=null;
String reason=null;
String planetld=el.getAttributeValue("planetld");
String field=el.getAttributeValue("field");
String value=el.getAttributeValue("value");
// @
Planet planet=findPlanet(planetld);
if (planet==null){
status-"failed";
reason="no planet found for id "+planetld;
}else{
Double numValue=new Double(value);
Object[] args=new Object[]{ numValue
};
String method = "set"+field.substring(O,1).toUpperCase()
+field.substring(1);
Statement statement=new Statement(planet,method,args);
try {
//
statement.execute();
status="ok";
} catch (Exception e) {
status="failed";
reason="unable to set value "+value+" for field "+field;
}
}
result.setAttribute("status",status);
if (reason!=null){
result.setAttribute("reason",reason);
}
return result;
}
private Planet findPlanet(String planetld)
{
// ORM
return null;
}
}

5. Ajax-

231

JDOM XML-, , .
processXML(). f indPlanet () ;
. f indPlanet () ; , .
.
, HTTP-.
, . 5.3,
JSF ,
.

.
, Aj -. , Ajax- ,
.

5.6.
Ajax-, . ,
,
. Web-,
, Ajax. , , , , , ,
.
: Model2, , .
, Ajax SOA,
.

232

II.


: , . Web ,
, Ajax , . , ,
. , , , XML .
JSON.
, ,
HTML- XMLHttpRequest.
Command.
, , . , ,
, ,
.
Ajax.
.
, , , , .

5.7.
.
URL.
Struts ( h t t p : / / s t r u t s . a p a c h e . o r g ) .
Tapestry ( h t t p : / / j a k a r t a . a p a c h e . o r g / t a p e s t r y / ) .
JSF
(http://java.sun.com/j2ee/javaserverfaces/faq.html).
PHP-MVC (http://www.phpmvc.net).
( h t t p : / / w i c k e t . s o u r c e f o r g e . n e t / I n t r o d u c
t i o n . h t m l ) , Java 60 .
JSF ,
. (Kito Mann), JavaServer Faces in
Action (Manning, 2004), Web-, JSF
(http://www.jsfcentral.com/). , (Greg Murray) Ajax JSF, https://bpcatalog.dev.java.net/nonav/ajax/jsf-ajax/
frames.html. AjaxFaces JSF Ajax
(http://www.ajaxfaces.com); . Apache Open Source MyFaces
(http://myfaces.apache.org/sandbox/inputSuggestAjax.html)
Ajax.

5. Ajax-

233

Microsoft Atlas
, .
Atlas, (Scott Guthrie), ,
Ajax (http://weblogs.asp.net/scottgu/archive/2005/06/28/
416185.aspx).
JSON-RPC, , http://www.json-rpc.org/impl.xhtml.

III

Ajax-
Aj- , . ,
, , . , ,
,
.

,
,

...

238 III. Ajax-

1 . ,
, , .
, . ,
, , . .
2-5 , , Ajax.
, . , . , .
, ,
. , ,
Ajax- .
, , , ,
"" . , , , . ,
, , , . Ajax-
, ,
.
, , . ,
, ,
.

6.1.
Ajax-,
.

. , ,
, Web-,
. , : Web- -

6.

239

.
. ,
- .
1 . , , .
, .

6.1.1.
, , .

. " ", .. ,
, , , .
,
. ,

, -,
USB, , .. Web- ; , , . Web ,
.
, . , 8.

6.1.2.
, , .
? , ? ,
, .
.
.
, .

240 III. Ajax-

?
. , , .
. ,
, . ,
, , ,
.
,
. ,
.
, . ,
.
, , , .
, ,
, . ,
""
.
, , , , . .

6.1.3.
, Ajax-
Web-. , Ajax, Bindows, qooxdoo Backbase, , , ,
, .
, ,
Web-, .
.
, ,
. Web- -

6.

241

, ,
.
. ,
, , ,
. ,
.
, , ,
- .

6.14.
. Ajax
.
, .
, ,
, . , , , ,
. , .
, .
,
, ,
. Ajax ,
, .

6.1.5.

. , ,
. . .
,
.
, ,
, .
,
. ,
, .

242 III. Ajax-

, Ajax-. , , , .
, . ,
.
, .
,
.

6.2.
Ajax- .
.

. ,

. .
, .
,
.

6.2.1.
. 5 .
, ,
(. 5.5). , , , ,
. 5.5.3 ;
, ,
. XML-, .
<commands>
<command id='001_diameter' status='ok' />
<command id='003_albedo' s t a t u s ' f a i l e d '
message='value out of range'/>
</commands>
, , , , . -

6.

243

, , . JavaScript- Command, , .
Command sent
.
. Command .
, . parseResponse () Command. 5.
planets.commands.UpdatePropertyCommand
.parseResponse=function(docEl){
var a t t r s = d o c E l . a t t r i b u t e s ;
var status=attrs.getNamedItem("status").value;
if (status!="ok"){
var reason=attrs.getNamedItem("message").value;
a l e r t ( " f a i l e d to update " + t h i s . f i e l d
+" to "+this.value+"\n\n"+reason);
}
}
.
, .
,
.
. , ,
, .
, . :
Failed to update albedo to 180 value out of range.
. ,
: Failed to update albedo of Mercury...,
, , .
. onblur. onblur () , ,
. , ,
. ,
, , ,
.
, .
, ,
. ,
.

244

III. Ajax-

12.2. ,

'
, .
, .
1 , Web-.
,
[ML- Command . ,
, (
[). , ,
, , , , .
, .
responses updateTime='1120512761877'>
<command id='001_diameter' status='ok'/>
<command id='003_albedo' s t a t u s = ' f a i l e d '
message='value out of range'/>
<update planetId='OO2' fieldName='distance 1
value='0.76' user='jim'/>
</responses>
<command>,
ommand, <update>,
.
, 0,76, Jim. , ,
.
,
. ,
, , . , . CommandQueue 6.1.
[ .
6.1. CommandQueue
//
net.cmdQueues-new A r r a y ( ) ;
//
net.CommandQueue=function(id,url,onUpdate,freq){
this.id=id;
net.cmdQueues[id]-this;
this.url=url;
this.queued=new Array();
this.sent=new Array();

6.
this.onUpdate-onOpdate;
// 0

if (freq){
this.repeat(freq);
}
this.lastUpdateTimeO;
}
net.CommandQueue.prototype.fireRequest=function(){
if (!this.onUpdate && this.queued.length==0){
return;
}
//
var data=
"lastUpdate"+this.lastUpdateTime
+"&data=";
for(var i=0;i<this.queued.length;i++){
var cmd=this.queued[i];
if (this.isCommand(cmd)){
data+=cmd.toRequestString();
this.sent[cmd.id]=cmd;
}
}
this.queued=new ArrayO;
this.loader=new net.ContentLoader(
this.url,
net.CommandQueue.onload,net.CommandQueue.onerror,
"POST",data
);
}
net.CommandQueue.onload=function(loader)
{
var xmlDoc=net.req.responseXML;
var elDocRoot=xmlDoc.getElementsByTagName("responses")[0];
var lastUpdate=elDocRoot.attributes.getNamedItem("updateTime") ;
if (parseInt(lastUpdate)>this.lastUpdateTime){
//
this.lastUpdateTime=lastUpdate;
}
if (elDocRoot){
for(i=0; KelDocRoot.childNodes.length;i++){
elChild=elDocRoot.childNodes[i];
if (elChild.nodeName-"command"){
var attrs=elChild.attributes;
var id=attrs.getNamedItem("id").value;
var command=net.CommandQueue.sent[id] ;
if (command){
command.parseResponse(elChild);
}
}else if (elChild.nodeName=="update"){
if (this.implementsFunc("onUpdate")){
//
this.onUpdate.call(this,elChild);
}
}

245

246 III. Ajax-


)
}
}
// 0
net.CommandQueue.prototype.repeat=function(freq){
this.unrepeat();
if (freq>0){
this.freq-freq;
var cmd="net.cmdQueues["+this.id+"].fireRequest{)" ;
this.repeater=setlnterval(cmd,freq*1000);
}
}
// /
net.CommandQueue.prototype.unrepeat=function(){
if (this.repeater){
clearInterval(this.repeater);
}
this.repeater=null;

, , .
-, Command .
,
s e t l n t e r v a l (), . CommandQueue , , .
CommandQueue
. onUpdate Function,
<update>, . freq , .
, repeat () , JavaScript s e t l n t e r v a l . s e t l n t e r v a l () setTimeout,
, , ,
, . , repeat () .
,
unrepeat () , c l e a r l n t e r v a l .
, , f ireRequest
. -.
onUpdate , , . ,
, , <update>. -

6.

247

, .
, . .
, Unix
, .. , 1
1970 . .
,

. Aj ax-,
.
onload () , <update>
0. onUpdate ,
DOM, <update>, .
, , , , 6.2.
6.2. updatePlanets()

function updatePlanets(updateTag){
var attribs=updateTag.attributes;
var planetld=attribs.getNamedltemC'planetld").value;
var planet=solarSystem.planets[planetld];
if (planet){
var fld=attribs.getNamedItem("fieldName").value;
var val=attribs.getNamedItem("value").value;
if (planet.fid){
planet[fId]=val;
}else{
alert('unknown planet attribute *+fld);
}
}else{
alert('unknown planet id '+planetld);
}
)

<update> ,
JavaScript. , , , , . , , a l e r t (). 6.2.1.
Command, , , , ,
, -

248 III. Ajax-

. ,
.
. -'
a l e r t () .

6.3.
a l e r t , , ,
JavaScript, Web- ,
.
CSS, , , , ,
Ajax.
.
,
, , . , ( Windows) , , , . .
, . ,
. . 6.1 ,
Unix.
lost+f ound ,
.
.
,
, . ,
.
, a l e r t () . , , , . , , , . .

. 6.1. , .
( ),
,
.
Unix,

6.3.1
,
, . , , , .
, , .
, ,
.
, .
,
,
. . , ,
,
. , , . ,
,
, .
Message, 6.3,
. . , .

250 111. Ajax-

6.3. Message
var msg=new Objectt);
|
rasg.PRIORITY_LOWb { i d : l , lifetime:30, icon:"img/msg_lo.png" J;
msg.PRIORITY_DEFAULT={ id:2, lifetime:60, icon:"img/msg_def.png" }; 1
msg.PRIORITY_HIGH= { i d : 3 , l i f e t i m e : - l , icon:"img/msg_hi.png" };
msg.messages=new Array();
I
msg.Message=function{id,message,priority,lifetime,icon){
this.id=id;
msg.messages[id]this;
this.message=message;
this.priority=(priority) ? priority : msg.PRIORITY_DEFAULT.id;
this.lifetime-(lifetime) ? lifetime : this.defaultLifetime();
this.icon(icon J ? icon : this.defaultlcon();
if (this.lifetime>0){
this.fader=setTimeout(
"msg.messages['"+thia.id+"'].clear()",
this.lifetime*1000
);
>
}
msg.Message.prototype.clear=function(){
msg.messages[this.id1null;
)
msg.Message.prototype,defaultLifetime=function(){
if (this.priority<=msg.PRIORITY_LOW.id){
return msg. PRIORITY__LOW. lifetime;
}else if {this.priority==msg.PRIORITY_DEFAULT.id){
return msg.PRIORITY_DEFAULT.lifetime;
}else if (this.priority>=msg.PRIORITY_HIGH.id){
return msg.PRIORITY_HIGH.lifetime;

j
',

msg.Message.prototype.defaultlcon=function(){
if (this.priority<=msg.PRIORITY_LOW.id){
return msg.PRIORITY_LOW.icon;
Jelse if (this.priority==msg.PRIORITY_DEFAULT.id){
return msg.PRIORITY_DEFAULT.icon;
Jelse if (this.priority>=msg.PRIORITY_HIGH.id){
return msg.PRIORITY_HIGH.icon;
}
_}
'_

msg, .
,
.
.
, , ( )
, . ( ).
, . , -1.

6. 251

. 6.2.
.

. 6.3.
, .

>

( . , ;
; , .

.2.

MVC, , .
, .
. , .
, (. 6.2).
X
. ,
; X.
. ,
^ ,
$ (. 6.3).
[ . , .
, ^ .
- (. 6.4), ,
.
I . , $& .
.
.

6.4.

: !
.
. , |
. Message |
<
, -*]
. :
.

6.4.1.
-'
, . Message.
MVC. ,
. , . .
,
. 6.4 ,
Message.
6.4. ' &^ < * * ~""~
//
rasg.Message.prototype.render=function(el){
if (this.priority<=msg.PRIORITY_LOW,id){
this.renderSmall(el);

6.
lelse if (this.priority>=msg.PRIORXTX_DEFAULT.id){
this.renderFull(el);
}
)
// @
//
msg.Message.prototype.renderSmall=function{el){
this.icoTd=document.createElement("div");
var ico=document.createElement("img");
ico.src=this.icon;
ico.classNarae="msg_smalI_icon";
this.icoTd.appendChild(ico);
this.icoTd.messageObj=this;
this . icoTd.onmouseover=msg.moverIconTooltip,this.icoTd.onmouseout=msg.moutlconTooltip;
this.icoTd.onclick=msg.clicklconTooltip;
el.appendChild(this.icoTd);
}
//
msg.moverIconTooltip=function(e){
var event=e || window.event;
var message=this.messageObj;
var popped=message.popped;
if ('popped){
message. showi?opup(event, f a l s e ) ;
}
}
//
msg.moutIconTooltip=function(e){
var message=this.messageObj;
v a r popped=rnessage.popped;
var pinned=message.pinned;
if {popped && 'pinned){
message.hidePopup();
}
)
/ / 0
msg.clickIconTooltip=function{e){
var event=e || window.event;
var message=this.messageObj;
var popped=message.popped;
var pinned=message.pinned;
var 6xpired=message.expired;
if (popped && pinned){
message.hidePopup{);
if (expired){
message.unrender();
}
}else{
message.showPopup(event.true);
}
}
//
msg.Message.prototype.showPopup=function(event,pinned){

253

III Ajax-

254

this.pinned=pinned;
if (!this.popup){
this.popup=document.createEleraent("dxv");
this.popup.className='popup' ;
this.renderFull(this.popup);
document.body.appendChild(this.popup);
}
this.popup.style.display='block1;
var popX=event.clientX;
var popY=event.clientY-xHeight(this.popup)-12;
xMoveTo(this- popup,popX,popY);
if {msg.popper && msg.popper!=this){
msg.popper.hidePopupf);
}
this.popped=true;
msg.popper=this;
}
//
msg.Message.prototype.hidePopup=function(){
i (this.popped){
if (this.popup){
this.popup.style.display='none' ;
}
this.popped=false;
}
__}

Message
. . render ()
DOM.
renderSmall() , renderFulK) .
, .
(. 6.2 6.3).
r e n d e r s m a l i o
DOM , .
Ajax- , .
.
,
, .
"" .
,
(
).

6.

255

6.4.2.
, . , (. 6.4).
,
. showPopupO, , renderFull {), .
.
, ,
. renderFull () 6.5.
!
6.5. renderFull
/
msg.Message.prototype.renderFull=functaon(el){

var inTable=(el.tagName=="TBODY");
var topEl=null;
this.row=document.createElement("tr");
if (!inTable){
topEl=document.createElement{"table") ;
var bod=document.createElement("tbody");
topEl.appendChild(bod);
bod.appendChild(this.row);
}else{
topEl=this.row;
}
var icoTd=document.createElement("td");
icoTd.valign=icenter' ;
this.row.appendChild(icoTd);
var ico=document.createElement{"img");
ico.src=this.icon;
icoTd.className="msg_large_icon";
icoTd.appendChild(ico);
var t x t T d = d o c u m e n t . c r e a t e E l e m e n t ( " t d " ) ;
txtTd.valign-'top' ;
txtTd.className="msg_text";
this.row.appendChild{txtTd);
txtTd.innerHTML=thi s.message;
el.appendChild(topEl);
_}

renderFull () .
DOM , <tbody>,
. <table> <tbody>. ,
,
<div> .

256 III Ajax-


*

, W3C DOM, innerHTML. HTML-


.

6.4.3.
.
render (),
6.6.
6.6. msg. render ()
msg.render=function(msgbar){
if (!msgbar){
msgbar='msgbar' ;
}
//
msg.msgbarDiv=xGetElementById(msgbar);
if (!msg.msgbarDiv){
msg.msgbarDiv=msg.createBar(msgbar);
}
styling.removeAllChildren(msg.msgbarDiv);
var lows=new Array();
v a r nveds=new A r r a y ;
var highs=new Array();
// @
for (var i in msg.messages){
var message=msg.messages[i];
if (message){
if (message.priority<=msg.PRIORITY__LOW.id) {
lows.append (message);
}else if (raessage.priority==msg.PRIORITY_DEFAULT.id){
meds.append(message);
Jelse if (message.priority>=msg.PRIORITY_HIGH.id){
highs.append(message);
}
}
}
//
for (var i=0;i<lows.length;i++){
lows fi].render(msg.msgbarDiv);
}
//
if (meds.length+highs.length>O){
msg.dialog=xGetElementByld(msgbar+"_dialog");
if (!msg.dialog){
msg.dialog=msg.createDialog(
msgbar+"_dialog",
msg.msgbarDiv,
(highs.length>0) );
// 0
}

6.
styling.removeAHChildren(msg.dialog.tbod);
for (var i=0;i<highs.length;i++){
highs[i].render(msg.dialog.tbod);
}
for (var i=0;Kmeds.length;i++){
meds[i].render(msg.dialog.tbod);
}
if (highs.length>0){
msg.dialog.ico.src=msg.PRIORITY_HIGH.icon;
}else{
msg.dialog.ico.src=msg.PRIORITY_DEFAULT.icon;
}
)
}
// 0
msg.createBar=function(id){
var msgbar=document.createElement("div");
msgbar.className='msgbar' ;
msgbar,id=id;
var parentEl=document.body;
parentEl.append{msgbar);
return msgbar;
}
//
msg.createDialog=function(id,bar,isModal){
var dialog=document.createElement("div");
dialog.className='dialog' ;
dialog.id=id;
var tbl=document.createElement("table");
dialog.appendChiId(tbl);
dialog.tbod=document.createElement("tbody");
tbl.appendChild(dialog.tbod);
var closeB-atton=document. createElement (" div" );
closeButton.dialog=dialog;
closeButton.onclick=msg.hideDialog;
var closeTxt=document.createTextNode("x");
closeButton.appendChild(closeTxt);
dialog.appendChild(closeButton);
//
if (isModal){
dialog.modalLayer=document.createElement("div");
dialog.modalLayer.className='modal' ;
dialog.modalLayer.appendChild(dialog);
document.body.appendChild(dialog.modalLayer);
}else{
dialog.clas sName+=' non-modal';
document.body.appendChild(dialog);
}
dialog.ico=document.createElement("img");
dialog.ico.className="msg_dialog_icon";
dialog.ico.dialog=dialog;
dialog.ico.onclick=msg-showDialog;
bar.appendChild(dialog.ico);
return dialog;
}

257

258 III Ajax-


//
msg.hideDialog=function(e){
var d i a l o g s ( t h i s . d i a l o g ) ? t h i s . d i a l o g : msg.dialog;
if (dialog){
if (dialog.modalLayer){
dialog.modalLayer.style.display='none' ;
}else{
dialog.style.display='none' ;
}
}
}
//
msg.showDialog=function(e){
var dialog=(this.dialog) ? this.dialog : msg,dialog;
if (dialog){
if (dialog.modalLayer){
1
1
dialog.modalLayer.style.display* block ;
}else{
dialog.style.display='block';
}
}
}

render () .
, , createDialog
createBar . DOM.
.

@. , , .
, DIV, , , . DIV
.
. CSS,
. CSS 6.7.
6.7. msg. ess
msg_small_icon{
height: 32px;
width: 32px;
position:relative;
float:left;
}
sg_jiialog_icon {
height: 32px;
width: 32px;

6.
position:relative;
float:right;
1
msg_large_icon{
h e i g h t : 64px;
w i d t h : 64px;
}
.msg_text{
font-family: a r i a l ;
font-weight: l i g h t ;
f o n t - s i z e : 14pt;
color: blue;
}
,msgbar{
position:relative;
background-color: white;
border: solid blue lpx;
width: 100%;
height: 38px;
padding: 2px;
}
.dialog{
position: absolute;
background-color: whiteborder: solid blue lpx;
width: 420px;
top: 64px;
left: 64px;
padding: 4px;
}
.popup{
position; absolute;
background-color: white;
border: solid blue lpx;
padding: 4px;
}
.non-modal{
}
.modal{
position: absolute;
top: Opx;
left: Opx;
width: 100%;
height: 100%;
background-image:url(img/modal_overlay.gif);

259

260

III. Ajax-

. 6.5. CSS- f l o a t
.
;

, GSb- msg_small_icon msg_dialog_icon


float. msg_small_icon , . , .
msg__dialog_icon .
.
; (. 6.5).
, Message, .
. 6.8
, ,
.
6.8. Message
var msg=new O b j e c t ( ) ;
msg.PRIORITY_LOWs= { i d : 1, l i f e t i m e : 30, i c o n : "img/msg_lo.png" } ;
msg.PRIORITY_DEFAULT={ i d : 2 , l i f e t i m e : 6 0 , icon:"img/msg_def.png" J;
msg.PRIORITY_HIGH= { i d : 3 , l i f e t i m e : - l , i c o n : "img/msg__hi .png" } ;
msg.messages=new A r r a y O ;
msg.dialog=null;
msg.msgBarDiv=null;
msg.suppressRender=false;
msg.Message=function(id,message,priority,lifetime,icon){
this.id=id;
msg.messages[id]=this;
this.message=message;
this.priority={priority) ? priority : msg. PRIORITY__DEFAULT. id;
this.lifetime=(lifetime) ? lifetime : this.defaultLifetime();
this.icon={icon) ? icon : this.defaultlcon();
if (this.lifetime>0){
this.fader=setTimeout(
"msg.messages['"+this.id+"'].clear()",
this.lifetime*1000
);
}
//
if (!msg.suppressRender){
this.attachToBar();

6.

261

}
}
// @
msg.Message.prototype.attachToBar=function(){
if (!msg.msgbarDiv){
msg.render();
}else if (this.priority==msg.PRIORITY_LOW.id){
this.render(msg.msgbarDiv);
lelsei
if (!msg.dialog){
msg.dialog=msg.createDialog(
msg.msgbarDiv.id+"_dialog",
msg.msgbarDiv,
(this.priority==msg.PRIORITY_HIGH.id)
);
}
this.render(msg.dialog.tbod);
msg.showDialog();
}
}
msg.Message.prototype.clear=function(){
msg.messages[this.id]=null;
// &
if (this.row){
this.row.style.display='none' ;
this. row.messageObj'^nullfthis.row^null;
}
if (this.icoTd){
this.icoTd.style.displays'none' ;
this.icoTd.messageObj=null;
this.icoTd=null;
}
_1

, . , . ,
. , ,
, , .
msg.render().
c l e a r ( ) , .
, ,
. , -

262 III Ajax-

.
ContentLoader .

6,5.
5 ContentLoader,
.
. .
, .
,
.
. , 4 5.
.
,
, .
, Message , :
, . ContentLoader
6.9.
..- ContentLoader
net.ContentLoader=function( ... )
{ ... } ;
net.ContentLoader.msgld=l;
net.ContentLoader.prototyped
loadXMLDoc:function{url,method,params,contentType){
if {Imethod){
method="GET";
}
if {IcontentType && method=="POST"){
contentType='application/x-www-form-urlencoded' ;

if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
} else if (window.ActiveXObject){
this.req=new ActiveXObj ect("Microsoft.XMLHTTP");

if (this.reqH
try{
var loader=this;
this.req.onreadystatechange=function(){
loader.onReadyState.call(loader);
)

6
this.req.open(method,url,true);
if (contentType)I
this.req.setRequestHeader('Content-Type' ,
}
//
this.notification=new msg.Message(
"netOO"+net.ContentLoader.msgld,
"loading "+url,
msg.PRIORITY_LOW.id,
-1,
"img/ball-earth.gif"
);
net.ContentLoader.msgld++;
this.req.send(params);
}catch (err){
this.onerror.call(this);
}
}

263

contentType);

onReadyState:function(){
var req=this.req;
var ready=req.readyState;
if (ready==net.READY_STATE__COMPLETE) {
var httpStatus=req.status;
if (httpStatus==200 || httpStatus==*O) {
this.onload.call(this);
// @
this.notification.clear{);
}else{
this.onerror.call(this);
}
}
},
//
defaultError:function(){
var msgTxt="error fetching data!"
+ "<ulxli>readyState: "+this. req.readyState
+"<li>status: "+this.req.status
+"<li>headers: "+this.req.getAHResponseHeaders()
+"</ul>";
if (this.notification){
this.notification.clear();

J
this.notifxcation=new msg.Message(
"net__errOO"+net. ContentLoader .msgld,
msgTxt,msg.PRIORITY__DEFAULT.id
);
net.ContentLoader.msgld++;
}

>^

264 III Ajax-


loadXMLDoct), ContentLoader.
, -1,
.
o n R e a d y S t a t e ( ) ). d e f a u l t E r r o r ( ) , >.
, H T M L .
6.10 , C o n t e n t L o a d e r
6.10. ,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Strict//EN"
"http://www.w3.org/TR/xhtmll/DTD/xhtmll-strict.dtd">
<btml>
<head>
<title>Notifications test<Vtitle>
<link rel=stylesheet type="text/css" href="msg.ess"/>
<script type="text/javascript" src="x/x_core.js"X/script>
<script type="text/javascript" src="extras-array.js"x/script>
<script type="text/javascript" src="styling.js"></script>
<script type="text/javascript" src="msg.js"></script>
<script type="text/javascript" src="net_notify.js"X/script>
<script type="text/javascript">
window.onload=function(){
msg.render('msgbar');
}
var msgld=l;
function submitUrl(){
var url=document,getElementById{'urlbar').value;
// .
var loader=new net.ContentLoader(url,notifyLoaded);
}
function notifyLoadedf){
// ,
var doneMsg=new msg.Message(
"done00"+msgld,
"loaded that resource you asked for: "+this.url,
msg.PRIORITY_LOW.id
);
msgld++;
msg.render('msgbar1);
}
</script>
</head>
<body>
<div class='content'>
<p>here is some content. This is what the web

265

. 6.6. ,


,

6.7.
,
(
;
)

application is up to when not being bugged silly


by all these messages and notifications and stuff.
<p>Type in a URL in the box below (from the
same domain, see Chapter 7 ) , and hit 'submit'.
A souped-up contentloader that understands the
notification system will be invoked.
<input id='urlbar' type='text1/>&nbsp;
<a href='javascript:submitUrl()'>submit</a>
</div>
<div id='msgbar' class='msgbar'></div>
</body>
</html>

Web- (. 6.6 6.7) HTML-,


URL. submit , URL .
notifyLoaded(). notifyLoaded() , ,
Message .
, . onload.
. , 6.9,
. -

266 III. Ajax-

,
, , .

ContentLoader ,
( onError
).
, ,
.
.

6.6.
, ,
, .
, , , .
ObjectViewer,
4 5, , ,
.

6.6.1.

; . ObjectViewer ,
. , ,
CSS, .
.new{ background-color: IfOeOdO; }
. ; , . 6.11 ObjectViewer, , , . .
6.11. ObjectViewer, ''
objviewer,PropertyViewer.prototype.commitEdit=function(value){
if (this.type=objviewer.TYPE_SIMPLE){
this.value=value;
var valDiv=this.renderSimple();
var td=this.valTd;
td.replaceChild(valDiv,td.firstChild);
this.viewer.notifyChange(this);

6.

267

//
this.setStatus(objviewer.STATUS_NEW);
}
}
objviewer.STATUS_NORMAL=1;
obj viewer.STATUS_NEW=2;
objviewer.PropertyViewer.prototype.setStatus=function(status){
this.status=status;
if (this.fader){
clearTimeout(this.fader);
}
if (status==objviewer.STATUS_NORMAL){
this.valTd.className='objViewValue' ;
}else if (status==objviewer.STATUS_NEW){
this.valTd.className='objViewValue new1 ;
var rnd="fade_"+new D a t e ( ) , g e t T i m e ( ) ;
this.valTd.id=rnd;
this.valTd.fadee=this;
// 0 -
this.fader=setTimeout("objviewer.age('"+rnd+"1)",5000);
}
}
objviewer.age=function(id){
var el=document.getElementById(id);
var viewer=el.fadee;
//
viewer.setStatus(objviewer.STATUS_NORMAL);
el.id-"";
el.fadee=null;
_}

: "" "". isNew,


. ; ,
,
. s e t S t a t u s () . CSS
"" . "" .
( ,
"", .
.)
, .

268

III Ajax-

. 6.8. O b j e c t v i e w e r

,

setTimeout(), DOM . , () . () " " .


. 6.8 Objectviewer .
"",
.
. .
, .

6.6.2.
Scriptaculous
. ,
.
Effect Scriptaculous,
"" .
3.5.2, ,

.
s e t s t a t u s ( ) , 6.11,
Scriptaculous. , ,
"'1 .
- Effect. Pulsate.
, , , . 6.12.

269

6.12. Scriptaculous
objviewer.PropertyViewer.prototype.setStatus=function(status){
this.status=status;
if (this.effect){
this.effect.cancel();
this.effect=null;
}
if (status==objviewer.STATUS_NEW){
this.effect=new Effect.Pulsate(
this.valTd,
{duration: 5.0}
)!
)

_J

Pulsate , -. age ().


Pulsate, DOM , .
Pulsate . , duration.
, , , . , .
( Scriptaculous 1.1 cancel ().)
, , , . .
.

6.7.
,
Ajax-.
, ,
, , .

.
, .
, -

270 111. Ajax-

,
. , .
, , .
ObjectBrowser, .
.
,
, .

6.8.
Scriptaculous Effects h t t p : //wihi . s c r i p t .
aculo.us/scriptaculous/list?category=Effects.
Nuvola, (David Vignoni)
(http://www.icon-king.com/).

...

Web-
,

Ajax

272

III Ajax-

-.
Web , Ajax-
.
, , ,
.
, .
Ajax ,
Web-. , Ajax. ,
, .
, , (, , ). , , Ajax. , ,
Ajax-, .
.

7.1. JavaScript
Ajax- Web- JavaScript-, ,
.
, . ,
, .
. , . Ajax-
Web- .
, . . , , .
, , . /
, , , . Ajax- JavaScript-
. ,
, -

7 Ajax-

273

. ,
, .
. , , , . , . ,
.

7.1.1. "-"
, Web- ,
" ", .
, , . , JavaScript-
, "" (sandbox).

. , Aj-
. Ajax-
, , . IFrame,
, ,
.
"-".
. .
=3;

.
alert(top.x+4);
. IFrame ,
(. 7.1).
,
a l e r t () .
.

7.1.2. Ajax-
, (. 5), JavaScript .
,
.
. -.
,

. ^ Ajax-
Web-

. 7.1. JavaScript
, ,

DOM-. , JavaScript, . Ajax , ,


.
, , , .
, ,
. , ,
.

7,1.3.
, , , ,
, . URL ,
IP-. . 7.1
, .
document. domain. , , ,
h t t p : //www.myisp. com/dave,
1
document.domain^'myisp.com ;
, http://dave.myisp.com/, , document. domain. ,
document.domain, www.google.com, .

7. Ajax-

275

7.1.
URL

http://www.mysite.com/
scriptl.j s
http://www.mysite.com/
cript2, js
s

h t t p : //www. my s i t e .com:
scriptl.js
h t t p : / /www. mys i t e . com/
script2.js

8080/


(
8080)

http://www.mysite.com/
scriptl. j s
h t t p s : / / w w w . m y s i t e . com/
s c r i p t 2 . js


(

HTTP)

http://www.mysite.com/
scriptl.js
http://192.168.0.1/
script2. js,


www.mysite.com

192.168.0.1,

http://www.mysite.com/
scriptl. j s
http://scripts.mysite.com/
script2.js

http://www.myisp.com/
d a v e / s c r i p t l . js
h t t p : //www.myisp, com/
e r i c / s c r i p t 2 . js


,

,

http://www.myisp.com/
d a v e / s c r i p t l . js
h t t p s : //www. my s i t e . com/
script2. j s

www.mysite.com

www.myisp. com/dave, HO

7.1.4.

. Internet Explorer "
" .

, ( ,
Internet Explorer 6). ,

ill

Ajax-

.
, Web-,
, . 7.2.
Ajax- ,
. Web-
.

Web-. Mozilla
. , , , , Web. Internet Explorer , , -.
, ,
Ajax-.
JavaScript , .
, Ajax, , .
, , .
, , Web-.
, , .

7.2.
, , ,
, . , , , . . ,
,
, .
. , .

7. Ajax-

277

. 7.3. ]-
, "-" ,
-

7.2.1.

"-" Ajax- . ,
, "-", (. 7.3).
, , "-". ,
.
. , ,

7.2.2. Web-
Web-,
, JavaScript,
. Ajax Web-.
''-". , , . , .
.
Ajax
Web-. Internet Explorer Mozilla Firefox -,
, .
, , Web- Google, SOAP (Simple Object Access Protocol). SOAP HTTP.
XML-, , XML-, .
XML-, SOAP, , "". XML XMLHttpRequest .
Google
SOAP.
XML-, . XML , Google .
, ,
URL. , .

. , .
(. 7.4). ,
Google ,
, 1000.
SOAP- Google XMLHttpRequest ContentLoader ( 3).
6,
.
ContentLoader Google, Internet Explorer, Mozilla.
.

7. Ajax-

279

. 7.4. API SOAP, Google, Ajax-,


. ,
Google,

Internet Explorer Web-


, Internet Explorer . Web-,
,
. Google, tentLoader, , , . 7.2. Yes,
, . No,
ContentLoader.
, .
, Ajax- Internet Explorer ,
.
Mozilla, Firefox,
, .
Mozilla PrivilegeManager
Mozilla . , , , Web- , .
, .
netscape.security.PrivilegeManager. , Ajax Google, PrivilegeManager.
Firefox , PrivilegeManager , , ,

280

III Ajax-

. 7.5. Firefox ,

. , , ,
intranet. ,
, , Firefox.
enablePrivilege.

, . 7.5.
, , .
. . , .
, .
, Internet Explorer , ,
. Mozilla
, , Remember my decision,
, . { ,
.) ,
.
ContentLoader ( 3,
5 6). , ,
Google.
PrivilegeManager ( 7.1). HTTP-.
SOAP.

7 Ajax-

281

7.1. C o n t e n t L o a d e r ,
net.ContentLoader=function(
url,onload,onerror, method, params,'contentType,
headers,secure
){
this.req=null;
this.onload=onload;
this,onerror=(onerror) ? onerror :
this.defaultError;
this.secure=secure;
this.loadXMLDoc(url,method,params,contentType, headers);
}
net.ContentLoader.prototype={
loadXMLDoc:function(url,method,params,contentType,headers){
if (!method){
method="GET";
}
if {!contentType && method=="POST"){
contentType^'application/x-www-foim-urlencoded1;
}
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
} else if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.req){
try{
try{
if (this.secure && netscape
&6 netscape.security,PrivilegeManager.enablePrivilege) {
//
netscape.security.PrivilegeManager
.enablePrivilege('UniversalBrowserRead1);
}
}catch (err)U
this.req.open(method,url, true) ;
if (contentType){
this.req.setRequestHeader('Content-Type', contentType);
}
// @ HTTP
if (headers){
for (var h in headers){
this.req.setRequestHeader(h,headers[h]);
}
}
var loader=this;
this.req.onreadystatechange=function(){
loader.onReadyState.call(loader);
}
this.req.send(params);
}catch (err){
this.onerror.call(this);

282

III. Ajax-
onReadyState:function(){
var req=this.req;
var ready=req.readyState;
i f (ready==net.READY_STATE_COMPLETE){
var httpStatus=req.status;
if (httpStatus==200 I I httpStatus==O){
try{
if (this.secure && netscape
&& netscape.security.PrivilegeManager.enablePrivilege) {
//
netscape.security.PrivilegeManager
.enablePrivilege('UniversalBrowserRead1);
}
}catch ( e r r ) { }
this.onload.call(this);
}else{
this.onerror.call(this);
}
}

_J

defaultError:function(){
a l e r t ( " e r r o r fetching d a t a ! "
+"\n\nreadyState:"+this.req.readyState
+"\nstatus: " + t h i s . r e q . s t a t u s
+"\nheaders: "+this.req.getAHResponseHeaders());
}
m

. HTTP 0.
SOAP. , , ,
.
, netscape.
PrivilegeManager,
. , : @. onload ReadyState (), .
Internet Explorer PrivilegeManager, .
t r y . . .catch, .
Internet Explorer, t r y . . . catch
. Mozilla PrivilegeManager .
ContentLoader Google. 7.2 HTML-, .

7. Ajax-

283

7.2. googleSoap.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Google Guessing</title>
<script type="text/javascript" src='net_secure.js'></script>
<script type="text/javascript" src='googleSoap.js'X/script>
<script type='text/javascript'>
var googleKey=null;
var guessRange = 1000;
var intNum = Math.round(Math.random()
* Math.pow(10,Math.round(Math.random()*8)));
window.onload = function(){
document.getElementById("spanNumber")
.innerHTML = intNum + " and "
+ (intNum + guessRange);
}
</script>
</head>
<body>
<form name="Forml" ons\ibmit="submitGuessO;return false;">
Obtain a search that returns between&nbsp;
<span id="spanNumber"></span>&nbsp; results!<br/>
<input type="text" name="yourGuess" value="Ajax">
<input type="submit" name="bl" value="Guess"/><br/xbr/>
<span id="spanResults"></span>
</form>
<hr/>
< t e x t a r e a rows='24( cols='100' id=' d e t a i l s ' X / t e x t a r e a >
</body>
</html>

HTML- .
googleKey. , API Google
SOAP. ,
.
.
.
URL, .

submitGuess (), sumit. JavaScript-. JavaScript- , API Google, 7.3.

284

111 Ajax-
7.3. submitGuess(}
f u n c t i o n submitGuess(){
//
if (igoogleKey){
a l e r t ( " Y o u w i l l n e e d t o g e t a l i c e n s e key "
+"from G o o g l e , \ n and i n s e r t i t i n t o "
+"the s c r i p t tag i n the html f i l e \ n "
+ " b e f o r e t h i s example w i l l r u n . " ) ;
return null;
}
var myGuess=document.Forml.yourGuess.value;
// SOAP
var strSoap='<?xml version="l.0" encoding="UTF-8"?>'
+ ' \n\n<SOAP-ENV:Envelope'
+ ' xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" '
+' xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"'
11 1
+ ' xmlns :xsd="http://www. w3.org/1999/XMLScherna >
+ ' <SOAP-ENV: BodyXns 1: doGoogleSearch'
+' xmlns:nsl="urn:Google3earch"'
+' SOAP-ENV:encodingStyle='
+'"http://schemas.xmlsoap.org/soap/encoding/">'
+'<key xsi:type="xsd:string">' + googleKey + '</key>'
+'<q xsi:type="xsd:string">'+myGuess+'</q>'
+'<start xsi:type="xsd:int">O</start>'
+'<maxResults xsi:type="xsd:int">l</maxResults>'
+'<filter xsi:type="xsd:boolean">true</filter>'
+ '<restrict xsi : type="xsd: string"X/restrict> '
+'<safeSearch xsi:type="xsd:boolean">false</safeSearch>'
+'<lr xsi:type="xsd:string"></lr>'
+'<ie xsi:type="xsd:string">latinl</ie>'
+'<oe xsi:type="xsd:string">latinl</oe>'
+ </nsl:doGoogleSearch> '
+'</SOAP-ENV:Body>'
+ '</SOAP-ENV:Envelope>' ;
// 0 ContentLoader,
// URL Google API
//
var loader=new net.ContentLoader(
"http://api.google.com/search/beta2",
parseGoogleResponse,
googleErrorHandler,
"POST",
strSoap,
"text/xml",
{
Man:"POST http://api.google.com/search/beta2 HTTP/1,1",
MessageType:"CALL"
},
true
);
}

7. Ajax-

285

submitGuess ()
. ,
. ,
null,
Google .
SOAP- , .
SOAP , ,
, XML- , . Internet Explorer Mozilla , SOAP.
, SOAP-
.
XML-, ContentLoader ,
SOAP XML HTTP-, URL API Google HTTP-. text/xml. , MIME-
, , ( ).
true, , PrivilegeManager.

ContentLoader , ( ) XML-. , Ajax.
<?xml version='1.' encoding='utf-8'?>
<soap~env:envelope
xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/1999/xmlschema-instance"
xmlns:xsd="http://www.w3.org/1999/xmlschema">
<soap-env:body>
<nsl:dogooglesearchresponse xmlns:nsl~"urn:googlesearch"
soap-env:encodingstyle="http://schemas.xmlsoap.org/soap/encoding/";
<return xsi:type="nsl:googlesearchresult">
<directorycategories
xmlns:ns2="http://schemas.xmlsoap.org/soap/encoding/"
xsi:type="ns2:array"
ns2:arraytype="nsl:directorycategory[1]">
<estimateisexact xsi:type="xsd:boolean">false</estimateisexact>
<estimatedtotalresultscount
xsi:type="xsd:int">741000</estimatedtotalresultscount>
<hostname xsi:type="xsd:string"></hostname>
<relatedinformationpresent xsi:type="xsd:boolean">true
</relatedinformationpresent>
<snippet xsi:type="xsd:string">de officinle site van afc

III. Ajax-

286

&lt;b&gt;ajax&lt;/b&gt;.</snippet>
<summary x s i : t y p e = " x s d : s t r i n g " > o f f i c i a l c l u b s i t e ,
i n c l u d i n g r o s t e r , h i s t o r y , w a l l p a p e r s , and Video c l i p s .
& l t ; b r s g t ; [english/dutch]</summary>
<title xsi:type="xsd:string">
&lt;b&gt;ajax&lt;/b&gt;.nl - splashpagina
</title>

SOAP- .
, , , , . ,
. 741000.
. 7.4 ,
.
7.4. parseGoogleResponse ()
J
function parseGoogleResponse(){
var doc=this.req.responseText.toLowerCase() ;
document.getElementBy!d( 'details').value=doc;
var startTag='<estimatedtotalresultscount xsi:type="xsd:int">';
var endTag='</estimatedtotalresultscount>';
var spotl=doc.indexOf(startTag);
var spot2=doc.indexOf(endTag);
var strTotall^doc.substring(spot1+startTag.length,spot2);
var t o t a l l = p a r s e l n t ( s t r T o t a l l ) ;
var strOut^"";
if(totall>intNum && totall<=intNum+guessRange){
strOut+="You guessed right!";
}else{
strOut+="WRONG! Try again!";
}
strOut+="<br/>Your search for <strong>"
+document.Forml.yourGues s.value
+"</strong> returned " + strTotall + " results!";
document.getElementByldf"spanResults").innerHTML = strOut;

_ J

SOAP-,
. XML-,
responseXML XMLHttpRequest.
. , DOM, , . ,
SOAP,
XML- .

7. Aj'ax-

287

PrivilegeManager Firefox
, PrivilegeManager .
,

, Firefox
, , ,
about :config. .
, ,
signed.applets.codebase_principal_support. true, . Google.
Mozilla ,
. Firefox, ,
true false . , ,
; , , ,
.
Mozilla
Internet Explorer PrivilegeManager,
.
Mozilla ,
(, , PrivilegeManager). ,
Remember my decision (. 7.5), , ,
.
,
. Web- . ,
JAR- , ,
HTML-, . JAR-
, , Thawte, VeriSign
, .
, JAR-. , .
jar:http://myserver/mySignedJar.jar|/path/to/someWebPage.html
Web-,
: .
Mozilla
JAR-. ,
, . keytool,
Java Development Kit (JDK).

288 III. Ajax-

,
.
JAR-
Mozilla. . ,
, .

Ajax . , , , , , .
, , . , ,
. ,
.

7.3.
, , ,
. ,
, ( ). HTTP-
, . , ,
.

7.3.1.
, Ajax, , ,
. ,
.
, .
(. 7.6),
, , , .
, , (, , ).
Ajax- HTTP
, .
, .
iFrame, HTML-, XMLHttpRequest . Web-, Ajax, , .

7. Ajax-

289

. 7.6. HTTP-

, ,
,

" ". ,
.

7.3.2. -
Ajax
, , , , . Hypertext Transfer Protocol Secure Socket Layer (HTTPS)
HTTP. , , ( ). " " - , ,
(. 7.7).
HTTPS , . HTTPS, ,
Web-, . HTTPS , JavaScript .
JavaScript DOM, CSS HTTP,

290

III. Ajax-

. 7.7.
HTTP-
,
, .


, ,
,

HTTPS ,
, .
HTTPS . , . ,
.
. . Web- HTTPS , ,
,
, HTTP. Ajax-
JavaScript, h t t p : / / h t t p s : / / . -,
HTTPS , .
, ,
,
.
HTTPS
. ,
. ,
HTTP .

7. Ajax-

291

7,3-3.
HTTP-
, Web-
. ,
, . JavaScript. ,
, .

,
. , .
MD5. ,
, . -,
. -, ,
, .
,
, 5-, . . ,
. MD5-
. , .
, Aj ax in action MD5- 8bd04bbe6ad2709075458c03b6ed6c5a.
. .
, , ,
. , . , .
MDS- . , ,
. . ,
, .
.
,
, , . . ,
, -

292

III. Ajax-

, .
.
(, ) , .
, abed. MD 5- Ajax in actionabed e992dc25b<373842023
f06a61f03f3787. wxyz. , )5- 3f2da3b3ee2795806793c56bf00a8b94.
, , . ,
, , , .

. .
.
JavaScript
, , MD5-.
, JavaScript (Paul Johnston). ,
.
<script type='text/javascript' src='md5.js'X/script>
<script type='text/javascript'>var encrypted=str_md5('Ajax');
// ...
</script>

MD5 . , 3, md5().
Java, security.MessageDigest , MD5. .NET Framework System .Security.Cryptography.MD5.
, ,
, ,
. ,
HTTPS,
.
, .
"-"
, .
" " ,
. , Web-
.

7. Ajax-

293

. 7.8.
Ajax


, HTTP.
Ajax-
.
Web- ,

,

7.4. Ajax
Ajax . , , , HTTP. (, ), . . 7.8.

.
, , API , eBay, Amazon Google. . ,
, .
-, Web-, API, , , ,
, . -, Web-.

7.4.1.
Web-, . ,
"". : , ,
. ,

294

III. Ajax-

, , .
Web- .
Ajax-
Web- , ,
HTTP- , , . , , , .

.
Web- HTML-, . Ajax- Web-, , .

, , , ,
, .
, . Ajax-
Web- . ,
API, . API HTTP, SOAP XML,
, .
" "
, API Web-
, . " ". Ajax , Web-.
,
, :
, .
. .
. , .
.
. ,
(. 7.9).

7. Ajax-

295

. 7.9. Ajax-,
" "
.

.

7.2. API
URL

clearBoard.do

positionShip.do

,
, (,),
(N.S.EwwW)

. . . .

. :
. API,
, . 7.-2.

.
. API . 7.3.

296 III. Ajax-


7.3. API,

URL
setupBoard.do

,

(,, , )

7.4. API ( ,
)
URL

guessPosition.do
"hit" () "miss" () "not
, your turn" ( )
(,)

, , 5 SOA. . ,
.

. ,
,
.
, .
,
. ,
- . API . 7.4.
,
URL guessPosition.do.
not your turn.
, . ,
API Web- . , ? ,
API
. , , p o s i t i o n S h i p . do . , , ,
. , , ,

.

7. Ajax-

297

, .
, .
, , ,
, . , API, ,
,
, , .
.
5.3.4 , API Fagade. , .
, , .
API - , , Ajax . .

7.4.2. Web
, , Ajax- (, , ) . , , , Ajax-
HTTP. , HTTP ,
, URL.
, HTTP , XMLHttpRequest
. , , .
HTTP-
Java. , . Web- Java
j a v a x . s e r v l e t . F i l t e r , .
F i l t e r d o F i l t e r ( ) , HTTP , . 7.5 , ,

298 III. Ajax-

, !
.
7.5. Java-,
public abstract class GenericSecurityFilter implements Filter {
protected String rejectUrl=null;
public void init(FilterConfig config)
throws ServletException {
// URL,
rejectUrl=config.getInitFarameter("rejectUrl"); }
public void doFilter(
ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
//
if (isValidRequest(request)){
chain.doFilter{request, response);
}else if {rejectUrl!=null){
// 0 URL,
RequestDispatcher dispatcher
=request.getRequestDispatcher(rejectUrl) ;
dispatcher.forward(request, response); }
}
protected abstract boolean
isValidRequest{ServletRequest request);
public void destroy{){}
}

, isValidRequest().
. isValidRequest () false,
U R L , Web- .

, .. .
-
. -. . ,
, 7.6.
7.6.
public class SessionTokenSecurityFilter
extends GenericSecurityFilter {
protected boolean isValidRequest(ServletRequest request) {
boolean valid=false;
HttpSession session=request.getSession() ;
if (session!=null){
UserToken token=(Token) session.getAttribute{'userToken');

7. Ajax-
if (token!-null){
valid=true;
}
}
return valid;
}
}

Web-. ,
. Ajax-
Web-
XML, JSON .
. 11
Ajax Portal.
HTTP-
. HTTP-
. 7.7 ,
, .

7.7. HTTP-
"!
public class SecretHeaderSecurityFilter
extends GenericSecurityFilter {
private String headerName=null;
public void init(FilterConfig config) throws ServletException {
super.init(config);
//
headerName-config.getlnitParameter("headerName");
}
protected boolean isValidRequest(ServletRequest request) {
boolean valid=true;
HttpServletRequest
hrequest=(HttpServletRequest)request;
if (headerName!=null){
valid=false;
//
String
headerVal=hrequest.getHeader(headerName);
Encrypter
crypt=EncryptUtils.retrieve(hrequest);
if (crypt!=null){
//
valid=crypt.compare(headerVal);
}
}
return valid;
}

^ww

III. Ajax-


,
. ;
, .
crypter )5- Apache Commons Codec
javax.security.MessageDigest.
, .
5- .
MessageDigest
digest=MessageDigest.getInstance("MD5");
byte[] data=privKey.getBytes();
digest.update(data);
byte[] raw=digest.digest(pubKey.getBytes());
byte[] b64=Base64.encodeBase64(raw);
return new String{b64);

privKey pubKey .
URL, /Ajax/data, web.xml
:
< f i l t e r id='securityFilter_I'>
<filter-name>HeaderChecker</filter-name>
<filter~class>
com.manning.aj axinaction.web.SecretHeaderSecurityFilter
</filter-class>
<init-param id='securityFilter_l_param_l'>
<param-name>rejectUrl</param-name>
<param-value>/error/reject.do</param-value>
</init-param>
<init-param id='securityFilter_l_param_2'>
<param-name>headerName</param-name>
<param-value>secret-password</param-value>
</init-param>
</filter>

secret-password URL / e r r o r / r e j e c t . d o . , ,
, .
<filter-mapping>
<filter-name>HeaderChecker</filter-name>
<url-pattern>/ajax/data/*</url-pattern>
</filter-mapping>
5- Base64 ( ). HTTP-, setRequestHeadert).
function loadXml(url){
var req=null;
if (window.XMLHttpRequest){
req=new XMLHttpRequest();

7. Ajax-
}
}
if

301

e l s e if (window.ActiveXObject){
req=new A c t i v e X O b j e c t ( " M i c r o s o f t . X M L H T T P " ) ;
(req)f
req.onreadystatechange=onReadyState;
req.open(GET',url,true);
req.setRequestHeader('secret-password',getEncryptedKey());
req.send(params);

}
}

5- Base64 .
var key="password";
function getEncryptedKey(){
return b64_md5(key);
}

Ajax- key. HTTPS . , , .


.
HTTP- HTML-. HTTP-,
. , XMLHttpRequest , , . , , Apache HTTPClient Perl LWP::UserAgent:
.
, , . ,
, ,
, , .
Ajax-. , . ,
Ajax, Web-. . HTTP-
, ,
( ). ,
Ajax-, , .
, , .
. , . HTTPS

302 . Aj'ax-

HTTP- , , ,
.

7.5.
Ajax-.
, Ajax Web-. "" ( JavaScript-
Web-) , , . , "-"
-, API Google.
, ,
. HTTPS, , HTTP. ,
Ajax-,
. ,
, . , .
, ,
Ajax- .
, . .

7.6.
API Web- Google , http://www.google.com/apis/.
JavaScript- , MD5, http://pajhome.org.uk/crypt/md5/
md5src.html. , MD5 , URL ( h t t p : //www. f i l e f ormat
.info/tool/hash.htm?text* ajax+in+action).
Apache Commons Codec Java, Base64 MD5 ,
h t t p : / / j akarta.apache.org/commons/codec/.
7.1 JAR- , Mozilla.
http://www.mozilla.org/projects/security/components/signed-scripts.
html. " " h t t p : / /
gamesmuseum.uwaterloo.ca/vexhibit/Whitehill/Battleship/.

...
Ajax

,

III. Ajax-

erJj
, , ,
. ,
.
, .
,
, "" ,
. , .. , ,
, .
. .
, .

8.1.
, ;
(
). ,
,
. , , , .
.
, , ,
. , , .
.
, .
, ,
, . , , .
, ,
, .
,
.
,
.
, Web-, . , -

8.

305

, DOM
-262, JavaScript, . " "
, . *
,
, ,
, , . , , 20 ,
15 , .
JavaScript ,
, . JavaScript
DOM . .
JavaScript- Ajax-, ,
. JavaScript- Ajax , Web-.
JavaScript Ajax- , Web- .
, .
, Ajax- DOM.

8.2. JavaScript-
, , .
" ". ( , , .)
, , , . ,
.
,
.
, .
, .
. , , , . ( ,
, .)

. U v l o in. ^ Ajax-

. .
, .
" '1 ,
. ,
. " " ,
.
. ,
JavaScript .
, .

8.2.1.
, , , JavaScript
Date. Date, , .
Date , . Date 8.1.
8.1. Date
function myTimeConsumingFunctionf){
var beginning=new Date{);
//
var ending=new Datef);
var duration=ending-beginning;
alert("this function took "+duration
+"ms to do something interesting!");

_J

Date ,
,
.
a l e r t ( ) , . , JavaScript
. ,
Aj ax- ,
.
, , ,
, , .
, DOM.

3.

307

8.2 , , .

, .
var stopwatch-new Object();
//
stopwatch.watches=new Arrayt);
//
stopwatch.getWatch=function(id,startNow){
var watch-stopwatch.watches[id] ;
if {!watch){
watch=new stopwatch.Stopwatch(id);
}
if (startNow){
watch.start();
}
return watch;
}
// ,
stopwatch.StopWatch=function(id){
this.id-id;
stopwatch.watches[idl-this;
this.events-new Array();
this.objViewSpec-[
{name: "count", type: "simple"},
{name: "total", type; "simple"},
{name: "events", type: "array", inline:true}
]?
)
stopwatch.Stopwatch.prototype.startefunction(){
this.current=new TimedEvent(};
}
stopwatch.Stopwatch.prototype.stop=function(){
if (this.current){
this.current.stop();
this.events.append(this.current);
this.count++;
this.total+=this.current.duration;
this.currentnull;
}
)
//
stopwatch.TimedEvent=function(){
this.start=new Date();
this.objViewSpec=[
{name: "start", type: "simple"},
{name: "duration", type: "simple"}
];
}
stopwatch.TimedEvent.prototype.stop=function(){
var stop=new Date ;
this.duration=stop-this.start;
1

308

fff Ajax-

. 8.1. -.
, .
s t o p w a t c h . w a t c h e s ,

//
stopwatch.report=fvmction(div){
var
realDiv=xGetElementById(div);
var
report=new
objviewer.ObjectViewer(stopwatch.watches,realDiv)I

- ,

.
stopwatch, s t a r t (), , stopwatch .
s t a r t () s t o p ( ) . stop() TimedEvent,
.
, s t a r t ( ) , ,
.

stopwatch, .
. 8.1.
. render {)
Object Viewer (. 5). CSV,
.
8.3 ,

8.3.

JUS

function myTimeConsuniingFvmctionO (
var vatch=stopwatch.getWatch("my time consuming function",true);
//
watch.stop();

, .
. .
,
.
Mousemat, 4. .
,
,
. ,
. ,
.
- . 8.4
Web-, DIV,
. , .
8.4. mousemat. html
<htmlxhead>
<link rel='stylesheet' type='text/ess1 href='raousemat.ess1 />
<link rel=lstylesheet1 type='text/ess1 href='objviewer.ess1 />
<script type='text/javascript1 src='x/x_core.js'x/script>
=1
<script type='text/javascript' src extras-array.js*></script>
<script type='text/javascript' src='styling.js'></script>
<script type='text/javascript' src='objviewer . js'x/script>
<script type='text/javascript' src='stopwatch.js'X/script>
<script type='text/javascript' src='eventRouter.js'x/script>
<script type='text/javascript'>
var cursor=null;
window.onload=function(){
var watch=stopwatch.getWatch("window onload",true);
var mat=docu-ment .getElementById( 'mouseraat' ) ;
cursor=document,getElementById('cursor' ) ;
var mouseRouter=new jsEvent.EventRouter(mat,"onmousemove");
mouseRouter.addListener(writestatus);
mouseRouter.addListener(drawThumbnail);
watch.stop();
}
function writeStatus(e)t
var watch=stopwatch.getWatch("write status",true);
window.status=e.clientX+","+e.clientY;

watch.stop();
}
function drawThumbnail(e){
var watch=stopwatch.getWatch("draw thumbnail",true);
cursor.style.left=((e.clientX/5)-2)+"px";
cursor.style.top=((e.clientY/5)-2)+"px";
watch.stop{);
}
</script>
</head>
<body>
<div>
<a href='j avascript:stopwatch.report("profiler")'>profile</a>
</div>
<div>
<div class='mouseinat' i d = ' m o u s e m a t ' x / d i v >
<div class='thumbnail' id='thumbnail'>
<div c l a s s = ' c u r s o r ' i d = ' c u r s o r p x / d i v >
</div>
<div c l a s s = ' p r o f i l e r objViewBorder' i d = ' p r o f i l e r < x / d i v >
</div>
</body>
</html>

: window.onload ~
. .
, .
, , ,
. . 8.2
,
.
Firefox Internet Explorer : ,
,
.
, window.onload 0 .
- ,
Date. JavaScript,
. Mozilla , .
.

8.2.2. Venkman
Mozilla -:
, . Venkman, JavaScript- -

8.

311

. 8.2. 4,
JavaScript ,
.
w i n d o w , o n l o a d ,
c o u n t ,
, a t o t a l
,

. Venkman
. , ,
.
Venkman, Tools . (, , Venkman
. .)
P r o f i l e (. 8.3).
.
Venkman
, JavaScript.
,
P r o f i l e ,
. Window
Profile=>Save P r o f i l e Data As. , CSV (
), HTML ( ) XML.
, Venkman
, URL chrome://. , JavaScript; . , HTML- , JavaScript, stopwatch.js>
. . 8.4 HTML-,
HTML-.

312 III Ajax-

8.3. Venkman Mozilla


P r o f i l e , ,
(
)

. 8.4. , Venkman
, , ,

, Venkman, , -, :
,
, .
Venkman ,
, -.
, . -.

313

8.2.3. Ajax-
, . JavaScript- Web-
-
Ajax-.
0>, . , , 8.2.1,
. ,
,
.
for
,
, .
JavaScript-,
Ajax-. . , ,
, .
, .
, :
1, 1, 2, 3, 5, 8, . . .
JavaScript,
, :
function fibonacci(count){
var a=l;
var b=l;
for (var i=0; Kcount; i++) {
var total=a+b;
a=b;
b=total;
)
return b;
}

,
. ,
, n- .
:
var total=0;
for (var i=0;i<fibonacci(count);i++){
total+=i;
}
, , ,
.

314 III. Ajax-

. , f ibonacci (count), , . for ,


.
, f ibonacci () .
var total=0;
var loopCounter=fibonacci(count) ;
for (var i=0;i<
loopCounter
;i++){
total+=i;
}

, . ? , ,
. , Web- -,
.
8.5.
8.5. f o r
<html>
<head>
<link rel=lstylesheet' type='text/ess' href='mousemat.css' />
<link rel='stylesheet' type='text/ess' href='objviewer.ess' />
<script type=' text/ javascript1 src=1x/x__core. js'x/script>
<script type='text/javascript' src='extras-array.js'X/script>
<script type='text/javascript1 src='styling.js'x/script>
<script type='text/javascript' src='objviewer.js'X/script>
<script type='text/javascript' src='stopwatch.js'X/script>
<script type='text/javascript' src='eventRouter.j s'X/script>
<script type='text/javascript'>
function slowLoop(count){
var watch=stopwatch.getWatch("slow loop",true);
var total=0;
//
for (var i=0;i<fibonacci(count);i++){
total+=i;
}
watch.stop();
alert(total);
}
function fastLoop(count){
var watch=stopwatch.getWatch("fast loop",true);
var total=0;
//
var loopCounter=fibonacci(count);
for (var i=0;i<loopCounter;i++){
total+=i;
}
watch.stop();
alert(total);
}
//

315

8.1. f o r

( )

3085

450

function fibonacci(count){
var a=l;
var b=l;
for{var i=0; K c o u n t ; i++) {
var t o t a l = a + b ;
a=b;
b=total;
}
return b;
}
function go(isFast){
var
count=parselnt(document.getElementById{"count").value);
if {count==NaN){
alert("please enter a valid number");
}else if (isFast){
fastLoop(count);
}else{
slowLoop(count);
}
}
</script>
</head>
<body>
<div>
<a h r e f = ' j a v a s c r i p t : s t o p w a t c h . r e p o r t ( " p r o f i l e r " ) ' > p r o f i l e < / a > & n b s p ;
< i n p u t i d = ' c o u n t 1 value='25'/>&nbsp;
<a h r e f = ' j a v a s c r i p t : g o ( t r u e ) ' > f a s t loop</a>snbsp;
<a h r e f = ' j a v a s c r i p t : g o ( f a l s e ) ' > s l o w loop</a>
</div>
<div>
<div c l a s s = ' p r o f i l e r objViewBorder 1 i d = ' p r o f i l e r ' > < / d i v >
</div>
</body>
</html>
_
slowLoopO fastLoopt) . ( ) .
,

.
, HTML-. ,
, 25. . . 8.1.

316 . /-

, , for .
. , .
Ajax.
DOM.
DONI
,
DOM, : document.body,
. DOM ,
. ,
.
, ;
.
, , , .
.
-,
DOM. ,
, ,
. .
var container=document.createElement("div");
container.className='mousemat';
var outermost=document .getEleinentById( 'top') ;
outermost.appendChildfcontainer);
for(var i=0;i<count;i++){
1
var node=dbcument.createElement('div ) ;
node.className='cursor' ;
node.style.position='absolute';
node.style.left=(4+parselnt(Math.random{)M92))+"px";
node.style.top=(4+parselnt(Math.random()M92)H"px";
container.appendChild(node);
outermost DOM, , , ,
DOM. ,
, count+1 . , .
var container=document.createElement("div") ;
container. classUame=lmouseniatl ;
var outermost=document.getElementByldf'top') ;
for(var i=0;i<count;i++){
var node=document.createElement('div') ;
node.className='cursor' ;
node.style.position^'absolute';
node.style.left={4+parselnt(Math.random()*492)>+"px";
node.style.top=(4+parseInt(Math.random()*492))+"px";

8.

317

container. appendChild(node);
)
outermost.appendChild(container);

, , . 8.6
, -
.
8.6. DOM
<html>
<head>
1
1
<link rel='stylesheet type='text/ess' href='mouseroat.ess />
1
<link rel='stylesheet' type='text/ess hre='objviewer.ess1 />
<script type='text/javascript' src='x/x_core.js'x/script>
<script type='text/javascript' src='extras-array. js'></script>
<script type=1text/javascript' src='styling.js'X/script>
<script type='text/javascript' src='objviewer.js'x/script>
<script type='text/javascript1 src='stopwatch.js'x/script>
<script type='text/javascript1 src='eventRouter. js'X/script>
<script type=1text/javascript'>
var cursor=null;
function slowNodes(count){
var watch=stopwatch.getWatch("slow nodes",true);
var container=document.createElement("div");
container,className='mousemat' ;
var outermost=document.getElementByldt'top');
//
outermost.appendChild(container);
for(var i=0;i<count;i++)I
var node=document.createElement('div1) ;
node.className='cursor';
node.style.position='absolute1 ;
node.style.left=(4+parselnt{Math.random()*492))+"px";
node.style.top=(4+parseIntiMath.randomO*'i92n+"px";
container.appendChild(node);
}
watch.stop();
}
function fastNodes(count){
var watch=stop-watch.getViatch("fast nodes", true);
var container=document.createElement("div");
container.className='mousemat' ;
var outermost=document.getElementById('top' ) ;
for(var i=0;i<count;i++){
var node-document.createElement['div') ;
node.className='cursor' ;
node.style,position='absolute';
node. style. left=H+parse!nt (Matti, random() *492)) +"px" ;
node.style.top=(4+parselnt(Math.random()*492))+"px";
container.appendChild(node);

// ,
outermost.appendChild(container);
watch.stop();

318 III. Ajax-


8.2. DOM

( )

641

681

461

}
function go(isFast){
var count=parselnt(document.getElementById("count").value);
if (count==NaN){
alert("please enter a valid number");
Jelse if (isFast){
fastNodes(count);
}else{
slowNodes(count);

</script>
</head>
<body>
<div>
<a href='javascript:stopwatch.report("profiler")'>profile</a>&nbsp;
<input id='count' value='640'/>Snbsp;
<a href=ljavascript:go(true)'>fast loop</a>snbsp;
<a href='javascript:go(false)r>slow loop</a>
</div>
<div id='top'>
<div class='mousemat' id='mousemat'></div>
<div c l a s s = ' p r o f i l e r objViewBorder 1 i d = ' p r o f i l e r ' X / d i v >
</div>
</body>
</html>
_

, ,
"" "" . , HTML-. ,
DOM .
640. . 8.2.
,
, . .
.
. (,
, .)
JavaScript.
" ".

8.

319

" "
3 JavaScript, , , .
. :
myGrandFather.clock.hands.minute
. , .
:
var hourHand=myGrandFather.clock.hands.hour;
var minuteHand=myGrandFather.clock.hands.minute;
var secondHand=myGrandFather.clock.hands.second;
, , ,
.
,
.
:
var hands=myGrandFather.clock.hands;
var hourHand=hands.hour;
var minuteHand=hands.minute;
var secondHand=hands.second;
, . ,
Java # , .
, JavaScript- ,
, , , ,
.
- .
, , .
, , , ,
. .
, , .
var earth={
physics:{
mass:10,
pos:{ x:250,y:250 },
vel:{ x:0, y:0 },
ace:I x:0, y:0 }
}
};
, physics, ;
.
.
, , , -

320

III Ajax-

.
, , .
;
, . ,
. ,
.
, : -
, . ( ).
var
grav=(earth.physics.mass*moon.physics.mass)/(dist*dist*gravF);
var xGrav=grav*(distX/dist);
var yGrav=grav*(distY/dist);
moon.physics.ace.x=-xGrav/(moon.physics.mass);
moon.physics-ace.y=-yGrav/(moon.physics.mass);
moon.physics.vel.x+=moon.physics.ace.x;
moon.physics.vel.y+=moon.physics..;
moon.physics.pos.x+=moon.physics.vel.x;
moon.physics.pos.y+=moon.physics.vel. y;

.
.
var mp=moon.physics;
var mpa=mp.acc;
var mpv=mp.vel;
var mpp-mp.pos;
var mpm^mp.mass;
var grav=(epm*mpm)/(dist*dist*gravF);
var xGrav=grav*(distX/dist);
var yGrav=grav*(distY/dist) ;
mpa.x=-xGrav/(mpm);
mpa.y=-yGrav/(mpm);
mpv.x+=mpa.x;
mpv.y+=mpa.y;
mpp.x+=mpv.x;
mpp.y+=mpv.y;

. , ,
. 8.7 Web-, .
8.7.
<htmlxhead>
< l i n k r e l = ' s t y l e s h e e t ' t y p e = ' t e x t / e s s ' href='mousemat.css' />
<link r e l = ' s t y l e s h e e t 1 t y p e = ' t e x t / e s s ' h r e f = ' o b j v i e w e r . e s s ' / >

<script type='text/javascript src='x/x_core.js'x/script>


<script type='text/javascript' src='extras-array.j s'></script>
1
<script type='text/javascript src^'styling.js'X/script>
=t
<script type text /javascript' src='objviewer. js'></scro_pt>
1
<script type='text/javascript src='stopwatch.js'X/script>
<script type='text/javascript' src^'eventRouter.js'X/script>
<script type='text/javascript'>
//
var moon={
physics:{
mass:1,
pos:{ x:120,y:80 },
vel:[ x:-24, y:420 },
ace:{ x:0, : }

1
};
var earth={
physics:{
mags:10,
pos:{ x:250,y:250 },
vel:{ x:Q, y:0 },
ace:{ x:0, : }

};
var gravF=100000;
function showOrbit(count,isFast){
//
var data=(isFast) ?
fastData(count) :
slowData(count);
var watch=stopwatch.getWatch("render",true);
//
var canvas=document.getElementBy!d('canvas' ) ;
var dx=data.max.x-data.min.x;
var dy=data.max.y-data.min.y;
var sx=(dx==0) ? 1 : 500/dx;
var sy=(dy==0) ? 1 : 500/dy;
var offx=data.min.x*sx;
var offy=data.min.y*sy;
for (var i=0;i<data-path.length;i+=10){
var datum=data.path[i];
var dpm=datum.moon;
var dpe=datum.earth;
var moonDiv=document.createElement("div");
moonDiv.className='cursor1;
raoonDiv.style.position='absolute' ;
moonDiv.style.left=parselnt((dpm.x*sx)-offx)+"px";
moonDiv.style.top=parselnt((dpm.x*sx)-offy)+"px" ;
canvas.appendChiId(moonDiv);
var earthDiv=document.createElement("div");
earthDiv.className='cursor' ;
earthDiv.style.position='absolute' ;
earthDiv.style.left=parselnt((dpe,x*sx)-offx)+"px";
earthDiv.style.top=parselnt((dpe.x*sx)-offy)+"px";
canvas.appendChiId(earthDiv);
}

III. Ajax-
watch.stop();
}
//
//
function slowData(count){
var watch=stopwatch.getWatch("slow orbit",true);
var data={
min:{x:0,y:0},
max:{x:0,y:0},
path:
};
}
watch.stop();
return data;
}
//
//
function fastData(count){
var watch=stopwatch.getWatch{"fast orbit",true);
var data={
min:{x:0,:0},
max:{x:0,y:0},
path:[]
};
}
watch.stop{);
return data;
}
function go{isFast){
var count=parselnt(document.getElementBy!d{"count").value);
if (count==NaN){
alert("please enter a valid number");
}else{
showOrbit(count,isFast);
}
}
</script>
</head>
<body>
<div>
<a href=ljavascript:stopwatch.report("profiler")'>profile</a>&nbsp;
<input id='count1 value='640'/>&nbsp;
<a href='javascript:go(true)'>fast loop</a>&nbsp;
=l
<a href javascript:go(false)'>slow loop</a>
</div>
<div id='top'>
<div class='mouseraat' id='canvas'>
</div>
<div class='profiler ob^ViewBorder' id='profiler'X/div>
</div>
</body>
</html>

8.

323

8.3.

( )

94

57

( )

702

. slowData() fastData() , . .

.
; , .
, , stopwatch,
.
showOrbit (). .
.
,
. ""
"" , . ,
. . . 8.3 , 640 .
, , . ,
,
, .
, , 760 ,
792 , .. 5,
40%. , , . ,
,
.
.
, ,
,
. , DOM
, ,
. ,

324 III. Ajax-

, ,
, .
. . ,
Ajax. ,
.
, ,
. .

8.3. JavaScript-
Ajax-.
, Ajax Web-.
.
, , .
, .
Web- Ajax
.
, ,
. (
,
.)
.

8.3.1,
.
,
, , . JavaScript "
", , . ,
, ,
,
.
" " , ,
, .
, -

,
( , , ).
, , ,
.
. , . ;
Person.
function Person(name){
this.name=name;
this.pets=new Array();}
.
, ,
.
Person.prototype.addPet=function(pet){
this.pets[pet.name]=pet;
if (pet.assignOwner){
pet.assignOwner(this);}
}
, ,
, .
this.removePet{petName)=function{
var orphan=this.pets[petName];
t h i s . pets[petNarrLe]=null,
i
(orphan.unassignOwner){
orphan.unassignOwner(this);)

, ,
addPet ()
removePet (). , ,
( , ).
: .
,
, ,
. (
.)
, :
function Cat(name){this.name=name;}
Cat.prototype.assignOwner=function(person){}
Cat.prototype.unassignOwner=function(person){}
-, .
. , , , , -
( ).

* III. Ajax-
f u n c t i o n Dog(name){this.name=name;}
Dog.prototype.assignOwner=function(person){
this.owner=person;}
Dog.prototype.unassignOwner=function(person){
this.owner=person;}

Cat Dog Pet, .


, "". Java # Pet, , ,
. , , ,
.
. .
1. jim Person
2. whiskers Cat
3. fido Dog
Person ( 1).
var jim=new Person("jim");
( 2). whiskers
addPet (), Cat
. jim whiskers, jim.
jim.addPet(new Cat("whiskers"));
jim ( 3). whiskers,
.
var fido=new Dog("fido");
j im.addPet(fido);

jim ( 4).
jim.removepet("whiskers") ;
, ( 5). ,
.
j im.removePet("fido");


( 6).
jim=null, , fido ( 7).
fido=null;
6 , jim,
null. fido f i d o . owner.

327

" " , , "" (heap), JavaScript.


1 7, fido null,
-i^m , .
,

, , ,
, , " '. fido jim,
, Person,
, .
fido , Cat
, .
,
fido, .
1. , ? , fido Person.
, Person
500 Cat, .
2. ? " ". jim fido , . ,
JavaScript , , j im fido
. , ,
, .
. , , ,
.
. , Ajax. .

8.3.2. Ajax
, , .
, , Ajax. Ajax- pa-

#* in. Ajax-

, , !
. .
4 Aj -, I
. , , JavaScript. . DOM , JavaScript-.
.
, .

4.3.1 ,
( )
DOM ( ).
, .
, .
function Button(value,domEl){
this,domEl=domEl;
this.value=value;
this.domEl.buttonObj=this;
this.domEl.onclick=this.clickHandler;
}
, DOM domEl . ,

Button.prototype.clickHandler=function(event){
var buttonObj=this.buttonObj;
var value=(buttonObj && buttonObj.value) ?
buttonObj.value : "unknown value";
alert(value);
}

,
Button, DOM; . , . value.
,
.
Button ,
. DOM
, .
DOM , ,
. ,
DOM, , Button,
" " ,
.

329

DOM,
JavaScript, , , , , DOM. ,
" ",
. (
, C + + . )
Button :
Button.prototype.cleanUp=function(){
this.domEl.buttonObj=null;
this.domEl=null;
}

DOM . DOM. , ,
, n u l l . DOM
,
.
, .
DOM
Ajax, ,
, DOM . Web- DOM
HTML-. Objectviewer,
4 5, (. 6) , . DOM . .
, .
DOM, W3C,
DOM. , , ,
" ".
. . document.getElementById().
function Message(txt, timeout){
var box=document.createElement("div");
box.id="messagebox";
box.classname="messagebox";
var txtNode=document.createTextNode(txt);
box.appendChild(txtNode);
setTimeout("removeBox('messagebox 1 )", timeout);
}

330

III Ajax-
f u n c t i o n removeBox(id){
var box=document.getElementByld(id);
i f (box){
1
box.style.displays'none ;
}
}

Message ()
,
, .
box txtNode
, Message () , ,
DOM.
- removeBox () DOM .
.
, , , . , , . , .
DOM , , " " , . ,
,
.
function removeBox(id){
var box=document.getElementByld(id);
if (box && box.parentNode){
box.parentNode.removeChild(box);
}
}
: (Remove By Hiding) (Remove By Detachment). Message
.
DOM , Button, ,
cleanUpO.
.

DOM. , , , , ,
.
, , ,
.

8.

331

, , DOM
. , , ,
. Message
:
function Message(txt, timeout){
var box=document.geElementById{"messagebox");
var txtNode=document.createTextNode(txt);
if (box==null){
box=document.createElement("div");
box.id="messagebox";
box.classname="messagebox";
box.style.display='block1;
box.appendChild(txtNode);
}else{
var oldTxtNode=box.firstChild;
box.replaceChild(txtNode,oldTxtNode);
}
setTimeout("removeBox('messagebox')",timeout);
}

. (Create
Always) (Create If Not Exists).
,
.
,
( ).
DOM, ,
DOM,

.
Ajax ,
,
, DOM. , DOM
.
DOM, ,
, .
, , Ajax-,
Internet Explorer.

332 III. Ajax-


Internet Explorer

" ",
. Internet Explorer ,
comp. lang. JavaScript .
DOM JavaScript.
.
,
:
function MyObject(id){
this.id=id;
this.front=document.createElement("div");
this.front.backingObj=this;

1
MyObject . DOM t h i s . f r o n t , DOM
t h i s .backingObj
JavaScript.

, , :
MyObject.prototype.finalize=function(){
this.front.backingObj=null;
this.front=null;
}
null, .
DOM ,

. (Richard Cornford) , DOM
( ).
, , ,
Ajax, . , ,
, .
Internet Explorer
CollectGarbageO- Internet Explorer
, ,
. , ,
.
, , .

8.

8 4.
,
.
, .
, , . , ,
.

8.4.1. ,

JavaScript-, Date, .
JavaScript ,
. , .
, , . , , . Windows Task
Manager, Unix top, . .
Windows Task Manager
Windows Task Manager (. 8.5) , Windows 95 98 . Windows
Task Manager ,
, .
,
<Ctrl+Alt+Delete>. Task Manager
. Processes.
, , ,
Firefox 38 .
Mem Usage. Windows
,
View=>Select Columns (. 8.6).
Memory Usage V i r t u a l Memory Size, . Memory Usage
, , Virt u a l Memory Size ,
. Windows- Mem Usage , a Virtual Memory Size
, ,
.

334

II!

Ajax-

. 8.5. Windows Task Manager



top
top, Unix
( Mac OS X), ,
Windows Task Manager (. 8.7).
Task Manager,
, , .
top , ,
, . top, , , GNOME System Manager.

,
, , . , . , , ,
.

. 8.6.
P r o c e s s e s Task Manager. V i r t u a l M e m o r y S i z e
,

. 8.7. t o p , , ,
,

. 8.8. Process Explorer



Windows. ,
,
Mozilla f irefox , 8 4.2

Process Explorer Sysinternal.com (. 8.8)


" ".
, Task Manager,
.
, , Internet Explorer Firefox.
. . (J. G. Webber) Drip ( ) , , Internet Explorer
. Web-
D0M, ,
(. 8.9).
Ajax-.
,

. 8.9. Drip
DOM Internet Explorer

. Aj -
, , .
, ,
.

8.4.2.

,
. Ajax , .
;
, .
, , ciickBox. ,
, .
:
function CiickBox(container){
this.x=5+Math.floor(Math.random*)*370);
this.y=5+Math.floor(Math.random()*370);
this.id="box"+contai-boxes.length;
this.state=0;
this.render();
container.add(this);

}
ClickBox.prototype.render=function(){
this.body=null;
if (this.body==null){
this.body=document.createElement("div");
this.body.id=this.id;
}
this.body.className='boxl';
this.body.style.left=this.x+"px";
this.body.style.top=this.y+"px";
this.body.onclick=function(){
var clickbox=this.backingObj;
clickbox.incrementState();
}
}
ClickBox.prototype.incrementState^function(){
if (this.state==O){
this.body.className='box2' ;
}else if (this.state==l){
this.hide{);
}
this.state++;
}
ClickBox.prototype.hide=function(){
var bod=this.body;
bod.className='' ;
}

ClickBox , . ,
. .

DOM, .
ClickBox , , (
) .
DOM div. DOM
backingObj.
Container,
ClickBox.
.
function Container(id){
this.id=id;
this.body=document.getElementByld(id) ;
this.boxes=new Array();
}
Container.prototype.add=function(box){
this.boxes[this.boxes.length]=box;
this.body.appendChild(box.body);
}
Container.prototype.clear=function(){

. 8.10. , ,
100 .

for(var i=Q;i<this.boxes.length;i++){
this.boxes[i].hide();
}
this.boxes^new Array();
report("clear");
newDOMs=0;
reusedDOMs=0;
}

. 8.10.
, , . ,
, .
,
DOM
.
,
HTML-, . , ,
, . .
Reuse DOM Nodes
, ClickBox
DOM ,
. ,
(. 8.3.2). , , :
ClickBox.prototype.render=function(){
this.bodyenull;

III Ajax-

340

if (reuseDOM){
this.body=document.getElementById(this.
id);
}
if (this.body==null){
this.body=document.createElement("div");
this.body.id=this. id;
newD0Ms++;
}else{
reusedDOMs++;
}
this.body.backingObj =this;
this.body.className='boxl';
this.body.style.left=this.x+"px";
this.body.style.top=this.y+"px";
this.body.onclick=function(){
var clickbox=this.backingObj;
clickbox.incrementState();
}
}

Unlink On Hide
ClickBox (
, Container. c l e a r ()),
, . . 8.3.2.
ClickBox.prototype.hide=function(){
var bod=this.body;
bod.className='box3';
if (unlinkOnHide){
bod.parentNode.removeChiId(bod};
}

Break Cyclic References



ClickBox. , n u l l D 0 M , ..
.
ClickBox.prototype.hide=function(){
var bod=this.body;
bod,className='box3' ;
if (unlinkOnHide){
bod.parentNode.removeChild(bod);
}
if {breakCyclics){
bod.backingObj=null;
this.body=null;
I
}


ClickBoxes . , ,
.
240 .
1. 100 popul a t e ().
2. 100 .
3. .
s t r e s s T e s t ( ) .
function stressTest() {
for (var i=Q;i<240;i++){
populate (100);
populate(100);
container.clear();
}
alert("done");

,
, ClickBox .
. ,

, . , ,
.
.
. , ""
. , . 240 ,
. , .
.
Windows Task Manager.
, , , . Unix
top (. 8.4.1).
, .

8.4.

Reuse
DOM Nodes

Unlink
On Hide

Break
Cyclic
References



(Internet
Explorer)

166

84,5

428

14,9

14,6

574

14,2

. .

8.4.3. 150
, Windows
Task Manager, ,
, .
. 8.4.
2,8 1 ,
Windows 2000 Workstation.
Internet Explorer 6.
11,5 . Mem Usage Processes
Task Manager (. 8.4.1).
, ,
. Ajax- "" ,
.
, .
. clickBox
15 .
80, 160 430 580 . , 11,5 ,
3,5 570 , .. 150 , . ,
.

8.

343

.
[ . , , A, D F, ,
Reuse DOM Nodes { 90%),
Unlink On Hide .
DOM , document .getElementById(), , . , Unlink on
Hide
( ). Unlink
on Hide , G
.
, "" :
.
Reuse DOM Nodes,
. , ,
, , . ,
. ,
, DOM,
: , , ,
.
, , DHTML, ,
.
, , . , , .
, ,
.
,
. , , , ,
, . , .
. -

344 III Ajax-

, , ,
, .
,
;
. ,
. , . , . .

8.5.
.
Ajax , , , .
, ,
.
, JavaScript, ,
Venkman.
, .
, .
,
. , , , ,
DOM Internet Explorer., , , ,
Windows Unix.
, , . , ,
.
, , , . , Ajax-, '""
. ,
. , .

8. 345

8^6.
0 .
Drip, , (Joel
Webber) Internet Explorer.
h t t p : / / w w w . o u t o f h a n w e l l . c o m / i e l e a k / .
Venkman ( h t t p : / / w w w . s v e n d t o f t e . c o m / c o d e / l e a r n i n g
_yenkman/advanced).
Process Explorer ( h t t p : / / w w w . s y s i n t e r n a l s . c o m ) .
Internet Explorer
http://msdn.microsoft.com/library/default.asp?url=/library/enus/lETechCol/dnwebgen/ie_leak__patterns . a s p . , (Richard Cornford), , Google Groups. c o r n f o r d j a v a s c r i p t f i x C i r c l e R e f s () ( URL
, ).

IV
Ajax
? Ajax,
Web-.
, . ,
.
,
Ajax: ,
,
. ,
PHP, Java, VB.Net # . ,
Web- , , . !

...

JavaScript
VB.NET


350

IV Ajax

- , -
.
, .
'
", . ,
.
Ajax, .
, , ,

( ).
JavaScript -1
, ,
Ajax.

9.1.
,
. , . (double-combo script). \
: ,
. , , .

9.1,1.
, , , . , JavaScript, Web-
JavaScript. ,
, .
. 9.1.
: , .
,
. ;
JavaScript . , , ,
(
). ,
JavaScript : -

. 9.1.

. 9.2.

.
. , ,
, .

9.1.2.

. onchange
submit (),
JavaScript- . , .
, , , ,
, .
. 9.2.

; , . , . 9.2. , ,

. 9.3. ,
Ajax

. 9.4. Ajax

. 9.5.
s e l e c t

9.2.
,
, . , ,
. ( JavaScript ), ,
.
. 9.4, .
. s e l e c t .
XMLHttpRequest,
. , . XML s e l e c t . XML- DOM XML, JavaScript.
, Ajax . ( DOM
XML- ) 9.4, , , ,
.

9.2.1.
select. , .
. 9.5.

9.1.


s e l e c t

,
"""


Ajax
;


. 9.1,
.
s e l e c t . , ,
. , . ,
XML. Ajax; ( ),
.
,
, .
,
. Ajax (
, ).
9.1, onchange, s e l e c t .
F i l l T e r r i t o r y O (JavaScript), , .

9.1.
<form name="Forml"> <select name="ddlRegion"
onchange="FillTerritory(this,document.Forml.ddlTerritory)">
<option value="-l">Pick A Region</option>
<option value="l">Eastern</option>
<option value="2">Western</option>
<option value-"3">Northern</option>
<option value="4">Southern</option>
</select> <select name="ddlTerritory"></select> </form>

9.

355

, 9.1, ,
f i l l T e r r i t o r y { ) . F i l l T e r i-itoryO .
, , , .
F i l l T e r r i t o r y (),
.

9.2.2. /
F i l l T e r r i t o r y () , . , .
, Ajax
JavaScript . , , , Ajax. ,
JavaScript n e t . j s ( ContentLoader), . , , HTML.
<script type="text/javascript" s r c = " n e t . j s " x / s c r i p t >
ContentLoader , ,
, ( ) , 3.
, .
Ajax,
F i l l T e r r i t o r y O , 9.2;
.
9.2. F i l l T e r r i t o r y U Ajax
<script type="text/javascript">
function FillTerritory(oElem,Target){
// ,
var strValue = oElem.options[
oElem.selectedlndex].value;
// URL
var url = "DoubleComboXML.aspx";
//
var strParams = "q=" + strValue +
"&f=" + oTarget.form.name +
"&e=" + oTarget.name;
//
var loaderl = new
net.ContentLoader(url,FillDropDown,null,
"POST",strParams);

. 9.6.

F i l l T e r r i t o r y () ,
onchange . s e l e c t . , , URL . , :
, ,
"-". , , q, - f,
s e l e c t . select
XML.
, . , Ajax.
, ContentLoaderO
URL, ,
, , HTTP .
FiliDropDown (),
, ContentLoader, , POST.
ContentLoader XMI*
9.4, ,
.

9.3. : VB.NET
, ,
XML. , SQL, XML,
. . 9.6.
ContentLoader
. q, . q SQL, , ,

357

"-" . ,
, XML . ,
, XML.

9.3.1- XML-omeema
XML, . , .
: , ,
.
XML selectchoice, selectElement,
entry. selectElement HTML , , . entry , optionText optionValue,
, .
9.3.
9.3. XML-
<?xml version="l.0" ?>
<selectChoice>
<selectElement>
<formName>Forml</formName>
<formElem>ddlTerritory</formElem>
</selectElement>
<entry>
<optionText>Select A Territory</optionText>
<optionValue>-l</optionValue>
</entry>
<entry>
<optionText>TerritoryDescription</optionText>
<optionValue>TerritoryID</optionValue>
</entry>
</selectChoice>

XML 9.3, , ''Select A Territory" (" "). , , . .


, , ,
XML- .

358

IV. Ajax

9.3.2.
VB.NET . , .
XML-,
. , entry "Select A Territory" . 9.4, .
, , , ,
XML.
Northwind SQL
Server (Microsoft).
9.4. DoubleConiboXML.aspx. vb: XML- ^
// Page_Load
Private Sub Page_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
//
Response.ContentType = "text/xml"
//
Dim strQuery As String
strQuery Request.Form("q")
Dim strForm As String
strForm *= Request.Form("f")
\
_ /
Dim strElem As String
strElem = Request.Form("e")
// SQL
Dim strSql As String = "SELECT " &
"TerritoryDescription, " & _
"TerritorylD" & _
" FROM Territories" & __
" WHERE regionid = " & _
strQuery & " ORDER BY " & _
"TerritoryDescription"
Dim dtOptions As DataTable
// SQL
dtOptions = FillDataTable(strSql)
// XML
Dim strXML As StringBuilder
strXML = New StringBuilder("<?xml " & _
"version=""l,0"" ?>")
strXML.Append{"<selectChoice>")
strXML.Append("<selectElement>")
strXML.Append("<formName>" & _
strForm & _
"</formName>")
strXML.Append("<formElem>" & _
strElem &
"</formElem>")
strXML.Append("</selectElement>")

9.

359

/ /
If dtOptions.Rows.Count > 0 Then
/ /
strXML.Append("<entry>")
strXML.Append{"<optionText>" & _
"Select A Territory" & _
"</optionText>")
strXML.Append("<optionValue>-l" & _
"</optionValue>")
strXML.Append("</entry>")
// XML
Dim row As DataRow
For Each row In dtOptions.Rows
strXML.Append("<entry>")
strXML.Append("<optionText:>" & __
row("TerritoryDescription") & _
"</optionText>")
strXML.Append("<optionValue>" & _
row("TerritoryID") & _
"</optionValue>")
strXML. Append. ("</entry>")
Next
End If
// XML
strXML.Append("</selectChoice>")
Response.Write(strXML.ToString)
End Sub
Public Function FillDataTable( _
ByVal sqlQuery As String) ___
As DataTable
Dim strConn As String = _
"Initial Catalog - Northwind; " fi _
"Data Source=127.0.0.1; " & _
"Integrated Security=true;"
Dim cmdl As _
New SqlClient.SqlDataAdapter{sqlQuery, _
strConn)
Dim d a t a S e t l As New DataSet
cmdl.Fill(dataSetl)
cmdl.Dispose()
Return d a t a S e t l . T a b l e s ( O )
End F u n c t i o n

_ _

text/xml, , XMLHttpRequest .
, ,
, HTML .
, , , .
,
. ,

, S Q e
. .
,
SQL,
. : TerritoryDescription TerritorylD T e r r i t o r i e s . WHERE
SQL. ,
, , ORDER BY TerritoryDescription. SQL . FillDataTable()
, .
, SQL,
XML , 9.2.
selectElement, formName formElem, .
: SQL - . , XML-
"Select A Territory" .
, DataTable , TerritoryDescription tionText. TerritorylD optionValue. "-" ,
DOM XML ( JavaScript). XML, selectChoice 0.
XML, ContentLoader , . ContentLoader
FillDropDown(),
XML-.
, .
, .
XML . ,
XML .

9.4.
, XML ,
, DOM JavaScript. getElementsByTag^'
Name {) "" .
DOM (
, Rolodex). -

9.

XML getElementsByTagName ()
, .

.4.1. XML
- ,
. s e l e c t , , XML . select,
.
ContentLoader XML,
FillDropDown(), 9.2.
FillDropDown() entry XML Option.
"-"', . 9.5 FillDropDown() .
9.5. XML-
/ / XML-
function FillDropDown(){
// select
var xmlDoc = this.req.responseXML.documentElement;
var xSel = xmlDoc.
getElementsByTagName('selectElement1)[01;
var strFName = xSel.
childNodes[0],firstChild.nodeValue;
var strEName = xSel.
childNodes[1].firstChild.nodeValue;
// select
var objDDL = document.forms[strFName].
elements[strEName];
objDDL.options.length = 0;
// XML-,
var xRows = xmlDoc.
getElementsByTagName('entry1
);
for{i=0;i<xRows.length;i++){
var theText = xRows[i].
childNodes[0].firstChild.nodeValue;
var theValue = xRowsfi].
childNodes[l].firstChild.nodeValue;
var option - new Option(theText, theValue);
try{ objDDL.add(option,null);
}catch (e){
objDDL. add {opt ion, - I ) ;
}
}
_ J

Ji

362

IV. Ajax

FillDropDown() ContentLoader. .
XML-. ContentLoader
FillDropDown() t h i s , ,
responseXML
documentElement , DOM
JavaScript . ,
, select,
. , selectElement,
getElementsByTagName ()
. @.
, select.
,
, 0.
. entry XML,
getElementsByTagName(). ,
, "-" . - entry ,
, .
, Option,
. t a r g e t , ,
. s e l e c t . a d d ( )
, t r y .. . catch,
. , - . HTML, ,
. . 9.7 , .
Eastern,
. Southern,
.
. 9.7, : , .
.
, CSS (Cascading Style Sheet ).

9.4.2.
.
, ..
. 9.7 , s e l e c t
, .
Eastern s e l e c t

. 9,7.

. 9.8.
s e l e c t
-

.
, .
<select name="ddlTerritory" style="width:200px"x/select>
, , , . Firefox, , ,
. Microsoft Internet Explorer
, 9.8.
, Internet Explorer, .

CSS
, Internet Explorer : 1
style="width:100px;_width:250px"
Internet Explorer , , . , Internet Explorer 250 ,
100 . "
" , , , , .
, .

9.5.
. , . , ,
. ,
, . , ,
. , , , .

9.5.1.
,- .
. , ,
.
, .
, , ,
. s e l e c t multiple. , size. s i z e ,
( ,
).
<select name="ddlRegion" multiple size="4"
onchange="FillTerritory(this,document.Forml.ddlTerritory)">
<option value="l">Eastern</option>
<option value=:"2">We3tern</option>
<option value="3">Northern</option>
<option value="4">Southern</option>
</select>

F i l l T e r r i t o r y < ) . s e l e c t ,
.
.
function FillTerritory(oElem,oTarget){
var url = 'DoubleComboMultiple.aspx1;
var strParams "f=" + oTarget.form.name + "&e=" + oTarget.name;
for(var i=0;KoElem.options.length;i++)[
if(oElem.options[i].selected){
strParams += "&q=" + oElem.options[i].value;
}
}
var loaderl = new
net.ContentLoader(url,FillDropDown,null,"POST",strParams);
}

, ,
, , .
.NET , ,
. ,
.
W H E R E SQL.
Dim strQuery As String - Request.Form("q")
Dim strWhere As String = ""
Dim arrayStrt) As String = strQuery.Split(",")
Dim i As Integer
For Each i In arrayStr
If strWhere.Length > 0 Then
strWhere - strWhere & " OR "
End If
strWhere = strWhere & " regionid = " & i
Next
Dim strSql As String = "SELECT " & _
" TerritoryDescription, " & _
" TerritorylD" & __
" FROM Territories" & _
" WHERE " & strWhere & _
" ORDER TerritoryDescription"

, , .

9.5.2.
( , ). ,
. onchange
, URL .

: jfl
e l s e switch-case. i f - e l s e , ^
, &.
. : , SQL , .
s e l e c t . , >
strElem.
onchange .
Dim strSql As String
If strElem - "ddlTerritory" Then
strSql = "SELECT TerritoryDescription, " $ _
" TerritorylD" & __
" FROM Territories" & _
WHERE " & strWhere & _
" ORDER BY TerritoryDescription"
Else
strSql = "SELECT Columnl, Column2" &
" FROM TableName" & __
" WHERE " & strWhere &
" ORDER Column2"
End If

( , ) , .

9.6.

_^_

, ? !
, ,
, , . , ! -
:
"" Ajax. net.ContentLoader,
3 5. , Ajax.
-'" Ajax, Ajax.
, , , .
net.ContentLoader , .
XMLHttpRequest, . . ,
, /.

API .

"" n e t . ContentLoader , .
, ,
, .
, net .ContentLoader, .

9.6.1. netContentLoader
, .
net.ContentLoader = function! component, url,
method,
requestParams ) {
// net.ContentLoader
this.component = component;
this.url = url;
t h i s . r e q u e s t P a r a m s = requestParams;
t h i s . m e t h o d = method;
}

. , component, , "".
, component
aj axUpdate () handleError ()
. . , u r l , URL, "" . method
HTTP-. GET POST. , questParameters key=value,
, . ,
. , sendRequest
, -'"
:
var s t r = "Eastern";
var aComp - new SomeCoolComponent(...);
var ajaxHelper = new net.ContentLoader( aComp,
"getRefreshData.aspx", "POST",
[ "query=" + str, "ignore_case=true" ]
);

API. :
.
-, ;
. \
- JavaScript,

. ^.
, . ( prototype.js, Ruby On Rails) -.
net.ContentLoader.prototype = {
// ,
methodl: f u n c t i o n ( a , b, ) {

//
method2: function() { },
method3: function(a) { }
};

. ?
,
"-" .
. "-" , , ~ .
( , ) . , ? , , , - ( ). , , ( ,
) . : API.
API , : . , , XMLHttpRequest . , !
, . , , "" ( 9.6),
.
9.6. getTransport
getTransport: function() {
var transport;
//
if { window.XMLHttpRequest )
t r a n s p o r t = new X M L H t t p R e q u e s t ( ) ;
// IE A c t i v e X
e l s e if { w i n d o w . A c t i v e X O b j e c t ) {
t r y { t r a n s p o r t = new ActiveXObject( r Msxml2.XMLHTTP') ; }
catch(err) {
1
t r a n s p o r t = new A c t i v e X O b j e c t ( ' M i c r o s o f t . X M L H T T P ) ;
}
}
return transport;
},

,
, ,
Ajax .

API . , ,
. , ,
,
. .
//

var a , b , c ;
var ajaxHelper = new n e t . C o n t e n t L o a d e r ( . . . );
ajaxHelper.sendRequest( "paraml=" + a, "param2=" + b,
"param3=" + );

, sendRequest,
9.7.
sendRequest: function() {

/ /
var requestParams = ( ] ;
for ( var i = 0 ; i < a r g u m e n t s . l e n g t h ; i++ ) {
requestParams.push(arguments[i]);
}
//
var request = this.getTransport();
request.open( this.method, this.url, true );
request.setRequestHeader( 'Content-Type',
'application/x-www-form-urlencoded');
//
var oThis = this;
request.onreadystatechange = function() {
oThis.handleAjaxResponse(request) } ;
//
request.send( this.queryString(requestParams) );

>-

.
.
, JavaScript
arguments, .
, ^ , . , - key=value.
. , , ,
, var.

370

IV. Ajax

JavaScript ,
varB , , , ?
,
.. JavaScript!
{, -
, ). , .
, .
getTransport, 9.6, XMLHttpRequest. , Content-Type ,
. request.
. , oThis. , , (onreadystatechange)
oThis. .
, ( ),
. ( .) Ajax
ajaxHelper.
Ajax. , , 1, queryString,
.
Ajax. queryStringHe , , , .
9.8.

queryStrxng: function(args)

//
var requestParams = [ ] ;
for ( v a r i = 0 ; i < t h i s . r e q u e s t P a r a m s . l e n g t h ; i++ )
requestParams.push(this.requestParams[i]);
}
//
for ( v a r j = 0 ; j < a r g s . l e n g t h ; j++ ) {
requestParams.push(args[j]);
}
var queryString - "";
if ( r e q u e s t P a r a m s SS r e q u e s t P a r a m s . l e n g t h > 0 ) {
f o r ( v a r i = 0 ; i < r e q u e s t P a r a m s . l e n g t h ; i++ ) {

9.

371

queryString += requestParams[i] + &';


}
queryString queryString.substring{0, queryString.length-1);
}
return

queryString;

,
net.ContentLoader, , sendRequest .
.
.
var helper = new net.ContentLoader{
someObj, someUrl, "POST",
["a-one", -b-twon]
);
var s t r = ajaxHelper.queryString(
["c-three", "d-four"]
);
s t r -> "a*=one&b=two&c=three&d=four"
, , , Ajax.
, , , . , sendRequest ,
onreadystatechange .
request.onreadystatechange function(){
oThis.handleAjaxResponse(request)
}

, handleAj axResponse. 9.9.


handleAjaxResponse: function(request) {
if ( request.readyState == net.READi_STATE_COMPLETE ) {
if ( this.isSuccess(request) )
//
this.component.ajaxUpdate(request);
else
//
this.component.handleError(request);
}
},
isSuccess:
function(request){
return request.status =e 0
II ( r e q u e s t . s t a t u s >= 200 && r e q u e s t . s t a t u s < 3 0 0 ) ;

, , , readys- '
t a t e ( ), t h i s , component,
. .
. ""?
. , . , ,
t h i s , component, handleError, , Ajax - .
,
.
.
, t h i s . component aj axupdate handleError. , JavaScript ,
.
! net .ContentLoader , Ajax
DHTML-, Ajax. DHTML, Ajax, ! , .

9.6.2.
net.ContentLoader,
, . ,
, ,
, ^ .
.
, ( ) HTML. . , ,
. , s e l e c t JSP
. , - HTML-, , .
, URL option.
, , .
, , , s e l e c t , , , .

( HTML-), , HTML-, , , 9.10.


<html>
<body>
<form name="Forml">
<select id="region" name="region" >
<options... >
</select>
<select i d = " t e r r i t o r y " name="territory" />
</form>
</body>
</html>

DoubleCombo, , . , , ,
, . ,
, 9.11.

9.11. HTML- . ' 5 !


<html>
<head>
<script>
function inj ectComponentBehaviors() {
var doubleComboOptions = {};
< ! DoubleCombo >
new DoubleCombo('region', 'territory',
1
DoubleComboXML.aspx', doubleComboOptions );
}
</script>
</head>
<body onload=
injectComponentBehaviors()"
>
<form name="Forml">
<select id="region" narae="region" >
<option value="-l">Pic]c A Region</option>
<option value="1">Eastern</option>
<option value="2">Western</option>
<option value="3">Northern</option>
<option value="4">Southern</option>
</select>
<select id="territory" name="territory" />
</form>
</body>
</html>


,
, ,
onload.
, <body> . . ,
. injectComponentBehaviors() , . , JavaScript, DoubleCombo
,
.
DoubleCombo
. injectComponentBehaviors() DoubleCombo,
. 9.12.
. . -9,12. DoubieComboDoubleCombo
function DoubleCombo( masterld, slaveld, url,
options ) {
/ /
this.master - document.getElementByld(masterld);
t h i s . s l a v e = document.getElementById(slaveld);
this.options = options;
t h i s . a j a x H e l p e r " new n e t . C o n t e n t L o a d e r ( t h i s , u r l , "POST",
o p t i o n s . r e q u e s t P a r a m e t e r s I I, );
//
-
this.initializeBehavior() ;
}

; DoubleCombo. , , . 9.2.
, DoubleCombo, URL . , ..
URL, , options.
, requestParameters. , options
, ,
. "" CSS
. ,
.

9.2.

m a s t e r l d ,
s e l e c t .
, s e l e c t
slaveld

,
s e l e c t .
s e l e c t

options

, ,

, :
this.ajaxHelper = new net.ContentLoader( t h i s , u r l , "POST",
options.requestParameters || []
>;
, , Ajax.
, , Ajax,
net.ContentLoader, . DoubleCombo ( t h i s )
ContentLoader. ,
URL Ajax
u r l , "POST" HTTP-.
, requestParameters ( , ) "" , Ajax.
, t h i s ,
DoubleCombo
net .ContentLoader. ,
aj axUpdate () handleError ().
, :
this.initializeBehavior{);

- -, . , , : . , , .
( DoubleCombo, ).
, . ,
, , - ( ,
net.ContentLoader).

DoubleCombo.prototype = {
// ... .
};

, . i n i t i a l i z e B e havior().
initializeBehavior: function() {
var oThis = this;
this.master.onchange = function() { oThis.masterComboChanged(); };
)/

. onchange
s e l e c t { HTML).
masterComboChangedO .
masterComboChanged: function() {
var query = this.master.options[
this.master.selectedlndex].value;
this.ajaxHelper.sendRequest( 'q=' + query );

, - . ,
, Ajax.
Ajax , . , sendRequest {)
XMLHttpRequest, ajaxUpdate (). .
ajaxUpdate: function(request) {
var slaveOptions = this.createOptions (
^/
request.responseXML.documentElement);
//
this.slave.length = 0;
//
for ( var i = 0 ; i < slaveOptions.length ; i++ )
try{
this.slave.add(slaveOptions[i], null);
}catch (e){
this.slave.add(slaveOptions[i] , -1) ;
}

XML- request
createOptions(), option
select. s e l e c t . createOptions(),
, , . , getElementContent (),
9.13.

9.13.
createOptions: function (ajaxRespon.se) {
var newOptions = [];
var entries = ajaxResponse.getElementsByTagName('entry');
for ( var i 0 ; i < entries.length ; i++ ) {
var text = this.getElementContent(entries[i],
'optionText') ;
var value = this.getElementContent(entries[i],
'optionValue') ;
newOptions.push( new Option{ text, value ) );
}
return newOptions;

getElementContent: function(element,tagName) {
var childEleraent = element.getElementsByTagName(tagName)[0];
return {childElement.text != undefined) ? childElement.text :
childElement.textContent;

,
XML .
, XML- :
<?xml version'* 1.0" ?>
<selectChoice>
<entry>
<optionText>Select A Territory</optionText>
<optionValue>-l</optionValue>
</entry>
<entry>
<optionText>TerritoryDescription</optionText>
<optionValue>TerritoryID</optionValue>
</entry>
</selectChoice>

createOptions () ent r y XML- optionText optionValue getElementContent ( ) . getElementContent () ,


IE- t e x t XML, ;
W3C textContent.

. , . , . !
, . ,
handleError (),
net.ContentLoad.er . . , ?
. -, ,

DoubleComtoo. ,
(, ?
. ,
, ?
function myApplicationErrorHandler(request) {
// ,
}
var comboOptions = { requestParameters: [
"paraml=one", "param2=two" ],
errorHandler: myApplicationErrorHandler

};
v a r doubleCombo new DoubleCombo(

'region', 'territory ,
'DoubleComboXML.aspx',
comboOptions ) ;

, myApplicationErrorHandler ().
, ,
. "!" GMail. , , . ,
- . , handleError ()
DoubleCombo.
handleError: function(request) {
if ( this.options.errorHandler )
this.options.errorHandler(request);
}

! - . , s e l e c t
,
. ... 1.
, 14:45, , . ", . ! ... !"
. "-!" . :
" , . ".
:
<form>
<select id="region" name="region"><select>
<select i d = " t e r r i t o r y " name="territory"></select>
<select id="subTerritory" name="subTerritory"X/select>
</form>
. HTML- Emacs,
. . .

<script>
function injectComponentBehaviors() {
var optsl * { requestParameters: "master=region" };
var opts2 = { requestParameters: "master=territory" J;
1
new DoubleCombo( 'region ,
'territory',
'DoubleComboXML.aspx', optsl );
new DoubleCombo( 'territory',
1
subTerritory',
'DoubleComboXML.aspx', opts2 );
</script>

, ,
. . : " ",
14:57.
: ", !" , . , ,
.

9.7.

s e l e c t .
JavaScript
s e l e c t . Ajax
, JavaScript. Ajax,
,
. Ajax Web-,
.
, , .


, , .
, ,
, . , ,
. , " " .
.

. . .



Rico
Prototype
JavaScript apply ()

Ajax
. Google Suggest , ,
( , , ). , , .
, ,
IPrame. Google
XMLHttpRequest.
, Ajax ,
- . , , . .
, - , . , ,
, , .

10.1.
Ajax
. , , , . , . ,
, , Google Suggest. .

10.1.1.
. ,

. - "type-ahead suggest
Ajax" .
, ,
.

10.1.
^

. ,

1 000 , 10-

,
,

56

, ,
;

,
(
)

"" ,

.
,

1.
2.
3.
4.

.
.
.
,
div, ..

, .
, , . , Ajax
( )..
, Ajax, . 10.1.
, , .
, ,
. ,
, , Ajax.
. ,
. , , - .
, .

. 10.1. Google Suggest ""


. ( , , Web-.)
, , , , . " "

.
,
.
. ,
.
, .
.

10.1.2. Google Suggest


Google Suggest . Google Suggest ,
, . . 10.1 ,
Google Suggest "".
. 10.1 . ,
Google, . , , Google . , Google
JavaScript, (,
JavaScript , ).

. 10.2.

Google Suggest

.
Google - . , ,
.
Google ( ).

- Ajax.

10.1.3. Ajax
. , Google, Amazon Yahoo!,
, . , ,
.

, . /. JavaScript,
. , ,
, .
.
; . JavaScript.
. 10.2.
, ,
Ajax, . , JavaScript.

, ,
. .
. , ,
, JavaScript
, ,
.
, .

10.2. : #
, ,
: , .
, , XML-,
.

10.2.1.
, .
Northwind (Microsoft), Products,
.
XMLHttpRequest.
, , .
JavaScript, .
JavaScript 10.1,
10.1. typeAheadData.aspx.cs
//
p r i v a t e void Page_Load(object sender,
System.EventArgs e)
{
// @
Response.ContentType - "text/html";
//
string strQuery =
Request.Form.Get("q").ToString();
string strAny = "";
//
if (Request.Form.Get("where").ToLower()
== "true")
{
strAny = "%";
}
// SQL
string strSql = "Select top 15 " +

10.

387

"ProductName, " +
"Productld FROM Products " +
"WHERE ProductName like '" +
strAny + strQuery + "%"
'" ORDER BY ProductName";
// 0
DataTable dtQuestions = FillDataTable(
strSql);
// JavaScript
System.Text.StringBuilder strJSArr =
new System.Text.StringBuilder(
"arrOptions = new Array(");
int iCount = 0;
//
foreach (DataRow row in
dtQuestions.Rows)
{
if (iCount > 0)
{ strJSArr.AppendC1,") ; }
strJSArr.Append("[");
strJSArr.Append("\"" +
row["ProductName"].ToString() + " \ " , " ) ;
strJSArr.Append("\"" +
row["Productid"].ToString() + " \ " " ) ;
strJSArr.Append("]");
iCount++;
}
strJSArr.Append(");") ;
// 0
Response.Write(strJSArr.ToString());
}
//
public static DataTable
PillDataTable(string sqlQuery)
{
string strConn = "Initial Catalog = "+
"Northwind;Data Source=127.0.0.1; "
"Integrated Security=true;";
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter cmdl = new SqlDataAdapter();
cmdl.SelectCommand new SqlCommand(sqlQuery,conn);
DataSet dataSetl = new DataSetO;
cmdl.Fill(dataSetl);
icmdl.Dispose();
conn.Close();
return dataSetl.Tables[0];

, 10.1, , JavaScript.
. . ,
, , text/html .

,
XMLHttpRequest. , q ,
. , ,
.
where. true,
% ,
SQL ,
, , . ,
: 15 .
.
,
JavaScript . , .
, JavaScript.
HTML, HTML-
. # , , ASPX-
.
- s.
<%@ Page Language="c#" AutoEventWireup="false"
\
Codebehind="TypeAheadXML.aspx.cs"
\
Inherits="ChapterlOCS.TypeAheadXML"%>
HTML,
ASPX-,
( JavaScript), .. DOM JavaScript
. ,
, .

10.2,2.
Ajax ,
JavaScript , . JavaScript Mozilla ,
.
. XMLHttpRequest HTTP POST,
, ,
, . . , 10.2. -

. 10.3. JavaScript,

, .
10.2.
//string strQuery =
Request.Form.Get("q")-ToString();
string strQuery = "a";
string strAny = "";
//if (Request.Form.Get("where").ToLower() =- "true")
//{
strAny = "%";
_ //}

,
"". , JavaScript , 10.3. ,
. ,

. , , ,
. . :
15. ,
, .
, .

10.3,
Ajax, XMLHttpRequest, DHTML-. .

10.3.1. HTML
HTML- , : .
. ,

.
<Enter>.
<Enter> .
. .
,
, . , ^
HTML-, 10.3.
10.3. HTML-
<form name="Forml" AUTOCOMPLETE="off" ID="Forml">
AutoComplete Text Box: <input type="text" name="txtUserInput" />
<input type="hidden" name="txtUserValue" lD="hiddenl" />
<input type="text" name="txtlgnore" style="display:none" />
</form>

10.3 . , .
, .
,
Internet Explorer DHTML.
. ,
t x t u s e r i n p u t , txtUserValue t x t l g n o r e . t x t l g n o r e , , CSS.
.
, . ,
JavaScript.

10.3.2. JavaScript
JavaScript .
(
).
/ .
HTML-,
.
. ,
, .
, span , .

. 10.4.

. 10.4 "" ,
. .
, .
<Enter>, . ,
, .
- ,
. , JavaScript, ,
.. Web-
.
JavaScript (Ajax)
Ajax,
JavaScript net.js
(. 3). ContentLoader, Ajax i f - e l s e .
<script t y p e = " t e x t j a v a s c r i p t " src="net.js"></script>
, JavaScript
src, . , CSS. , ,
.
, ,
. ,
.

span
. 10.4 , . 0
span HTML, .
. span ,
.
10.4 span DOM
( onload). span HTML
spanOutput CSS span Text Dropdown. span. CSS , span .

, CSS
.
10.4. JavaScript,
window.onload = function(){
var elemSpan = document.createElement("span");
elemSpan.id "spanOutput";
elemSpan.className = "spanTextDropdown";
document.body.appendChild(elemSpan);
_}

span onload.
> .
DOM, createElement.
span
ID className. ,
. CSS ( 10.5),
.
10.5. CSS
span.spanTextDropdown{ position: absolute;
top: Opx;
left: Opx;
width: 150px;
z-index: 101;
background-color: #C0COCO;
border: lpx solid #000000;
padding-left: 2px;
overflow: visible;
display: none;
2

span ,
top l e f t .

0 z-index,
. CSS
, . display , .
, display
, .


, , . . , , , , , .
, , ,
. ,
, , , . 10.6
, , , .
10.6.
function SetProperties(xElem,xHidden,xserverCode,
xignoreCase,xmatchAnywhere,xmatchTextBoxWidth,
xshowNoMatchMessage,xnoMatchingDataMessage,xuseTimeout,
xtheVisibleTime){
var props={
elem: xElem,
hidden: xHidden,
serverCode: xserverCode,
regExFlags: { (xignoreCase) ? "i" : "" ),
regExAny: ( (xmatchAnywhere) ? " " : " " ) ,
matchAnywhere: xmatchAnywhere,
matchTextBoxWidth: xmatchTextBoxWidth,
theVisibleTime: xtheVisibleTime,
showNoMatchMessage: xshowNoMatchMessage,
noMatchingDataMessage: xnoMatchingDataMessage,
useTimeout: xuseTimeout

1;
AddHandler(xElem) ;
return props;


s e t P r o p e r t i e s (), . . ,
; ,

; URL , , ;
; , " "; , , ; ,
.
,
. . JavaScript Object Notation (JSON)
. , . ignoreCase
matchAnywhere .
. i " " "
.
, ,
if .

. , .
, S e t P r o p e r t i e s ( ) . , 10.7, onload ( )
.

10.7. ,
.^^^^^
window.onload = function(){
var elemSpan = document.createElement("span");
elemSpan.id = "spanOutput";
elemSpan.className = "spanTextDropdown";
document.body.appendChild(elemSpan);
document.Forml.txtUserlnput.obj =
SetProperties(document.Forml.txtUserlnput,
document.Forml.txtUserValue,'typeAheadData.aspx',
true,true,true,true,"No matching Data",false,null);
}

. , window.onload,
span.
.
,
,
>bj. , ,
.

10.

395

S e t P r o p e r t i e s O .
, 10.6. , , ., typeAh.eadData.aspx,
10.1. , onload , , S e t P r o p e r t i e s O
, , ,
.
: - ,
.
, 10.8.
10.8. , - ;
var
isOpera=(navigator-userAgent.toLowerCase(). indexOf{"opera")!= -1) ;
function AddHandler(objText){
objText.onkeyup = GiveOptions;
o b j T e x t . o n b l u r = function(){
if(this.obj.useTimeout)StartTimeout();
1
i f ( i s O p e r a ) o b j T e x t . o n k e y p r e s s = GiveOptions;
_}
m
10.8 , . , , Opera ,
. , Opera, ,
.
AddHandler () .
onkeyup onblur. onkeyup GiveOptions ()
. , , GiveOptions
.
onblur, , StartTimeout () ( 10.19)
, . , ,
<>.
Opera?
, onkeyup,
, onkeyup Opera -

396

IV. Ajax

, . ;.\
onkeypress.
,
isOpera, onkeypress. Opera
, . , ,
GiveOptions ().

GiveOptions (),
. :
, Ajax

. , GiveOptions ()
, , 10.1.1.
, .
,
. , , 10.9.
10.9. ,
var
var
var
var
var
var
var
var

arrOptions = new Arrayf);


strLastValue = "";
bMadeRequest;
theTextBox;
objLastActive;
currentValueSelected = -1;
bNoResults = false;
isTiming = false;

\.
\
\
\

arrOptions , . strLastValue ,
. bMadeRequest , , (
).
, , Google Suggest.
theTextBox , , a objLastActive . ,
.
, , ,
. . currentValueS-

10

greeted, selectedlndex . - 1 , .
bNoResults. , , .
^sTiming , . ,
.
, ,
. , .
, GiveOptionsO, . GiveOpt i o n s ( ) , 10.10, , .
10.10. JavaScript,
//
function GiveOptions(e){
var intKey -1;
if(window.event){
intKey = event.keyCode;
theTextBox = event.srcElement;
}
else{
intKey = e.which;
theTextBox = e.target;
}
//
if(theTextBox.obj.useTimeout){
if(isTiming)EraseTimeout();
StartTimeout();
}
II ,
if(theTextBox.value.length == 0
&& !isOpera){
arrOptions = new ArrayO;
HideTheBox();
strLastValue = "";
return false;
}
//
if(objLastActive == theTextBox)(
if(intKey 13){
GrabHighlighted();
theTextBox.blur();
return false;
}
else if(intKey == 38){
MoveHighlight(-l);
return false;
}
else if(intKey == 40){
MoveHighlight(l);
return false;

// ,
if(objLastActive != theTextBox ||
theTextBox.value
.indexOf{strLastValue) != 0 ||
((arrOptions,length==0 ||
arrOptions.length==15 )
SS IbNoResults) ||
(theTextBox.value.length
<= strLastValue.length)){
objLastActive = theTextBox;
bMadeRequest = true
TypeAhead(theTextBox.value)
}
else iff!bMadeRequest){
BuildList(theTextBox.value);
}
// ,
strLastValue = theTextBox.value;
}

, , , .
, B u i l d L i s t O ,
. ,
" ".
GiveOptionsO , . intKey,
. , , , . window.event Internet Explorer. -'
, event. keyCode,
, , event.srcElement.

.which, . t a r g e t .
, ,
.
obj ( ) useTimeout. ,
, EraseTimeout() StartTimeout() (
" JavaScript").
, - .
, HideTheBoxO ( " "), strLastValue n u l l , false, . , .

10.

399

<Enter>,
, .
, ,
<Enter>. 13 . <Enter>
. , GrabHighlighted() ( " ").
.
,
38 40 . - . , . 10.4,
- . ,
. , " ". , MoveHighlight () 1,
' - 1 .
"" , ,
, , . , ( ). ,
, .
, . , ,
, .
, .
, . ,
. objLastActive . , ,
( ,
), TypeAhead(), .

. ,
, . ,
.

400

IV. Ajax

10.3.3.
xMLHttpRequest
.
, , 10.1
, . 10.11, ContentLoader
, ,
, .
10.11. Ajax, \
function

TypeAhead(xStrText){

var strParams "q=" + xStrText +


"&where=" + t h e T e x t B o x . o b j . m a t c h A n y w h e r e ;
v a r l o a d e r l = new n e t . C o n t e n t L o a d e r (
theTextBox.obj.serverCode, BuildChoices,null,"POST",strParams);
)

TypeAhead() GiveOptions () (
) . , strParams, , matchAnywhere.
10.1 . , ContentLoader. ContentLoader
URL JavaScript,
. n u l l ,
.

. ContentLoader
, strParams.
BuildChoicest), . ,
JavaScript. "" . . ,
JavaScript. , , ContentLoader e v a l ( ) , 10.12.
10.12. responseTextB JavaScript
function BuildChoices(){
var strText = this.req.responseText;
eval(strText);
BuildList(strLastValue);
bMadeRequest = false;

10.

401

responseText Ajax.
JavaScript, e v a l O , , . ,
.
, JavaScript. , eval {) -
.
XML-
. B u i l d L i s t , . , bMadeRequest false,
, .

JavaScript DHTML.
. . 10.4,
,
, .
span.
BuildList ( ) , 10.13. : ,
.
10.13.
function BuildList(theText){
SetElementPosition(theTextBox);
//
var theMatches - MakeMatches(theText);
//
theMatches = theMatches.join().replace{/\,/gi,"");
//
if(theMatches.length > 0){
document.getElementByld("spanOutput")
.innerHTML = theMatches;
document.getElementByldf
"OptionsList_0").className =
"spanHighElement";
currentValueSelected = 0;
bNoResults = false;
}
/ / H e
else{
currentValueSelected = - 1 ;
bNoResults = true;
if{theTextBox.obj.showNoMatchMessage)
document.getElementByld(
"spanOutput").innerHTML =

402

IV. Aj'ax
"<span
class='noMatchData'>"
theTextBox.obj
. noMa.tchinqDataMessa.ge
+
"</span>";
else
HideTheBox();

}
_ J

B u i l d L i s t O , 10.13,
, . , , span
, . SetElementPositionO ( , " ").
span , , MakeMatches()
( " ").
, , .
, JavaScript .
MakeMatches () . ,
join. 0, , innerHTML.
className,
.
, " matches" (" "), .
, , , currentselectedValue - 1 .
, .
, BuildListO
, .
SetElementPosition().

. DHTML, .
, (
), .
.
, . , -

10.

403

JavaScript
.
10.14.
10.14.
function SetElementPosition(theTextBoxInt){
var selectedPosX - 0;
var selectedPosY = 0;
var theElement theTextBoxInt;
if (!theElement) return;
var theElemHeight = theElement.offsetHeightr
var theElemWidth = theElement.offsetWidth;
while(theElement != null)I
selectedPosX += theElement.offsetLeft;
selectedPosX += theElement.offsetTop;
theElement = theElement.offsetParent;
}
xPosElement document.getElementById("spanOutput");
xPosElement.style.left = selectedPosX;
if(theTextBoxInt.obj.matchTextBoxWidth)
xPosElement.style.width theElemWidth;
xPosElement.style.top = selectedPosY + theElemHeight
xPosElement.style.display = "block";
if(theTextBoxInt.obj.useTimeout){
xPosElement.onmouseout = StartTimeout;
xPosElement.onmouseover = EraseTimeout;
}
else{
xPosElement.onmouseout null;
xPosElement.onroouseover *= null;
}
_}

10.14 SetElementPosition(), : .
, selectedPosX selectedPosY, 0. .
.
offsetHeight offsetWidth.

while. X
.
, , .
,
, . obj , , width . true,

IV Ajax

404

. false,
, . , , ,
. display block.
:
. , .

, ,
, . MatchesO, , , , .
, ,
. , 10.15, ,
.

.
;: 10.15.
var countForld = 0;
function MakeMatches(xCompareStr){
countForld = 0;
var matchArray = new Array();
var regExp = new RegExp(theTextBox.obj.regExAny +
xCompareStr,theTextBox.obj.regExFlags);
for(i : =0;i<arrOptions.length;i++) {
var theMatch = arrOptions[i][0].match(regExp);
if(theMatch){
matchArray[matchArray.length]=
CreateUnderline(arrOptions[i][0], xCompareStr,i);

MakeMatches (), :
, . countForld 0 matchArray. ( , countForld .
.
.) , , ,
.
, , 10.6,
. regExAny,
, -

10

405

$# regExFlags , .
arrOptions, ,
. ,
matchArray CreateUnd e r l i n e ( ) , , .
, BuildList{),
. MakeMatches() , .
,
. CreateUnderline (), .

,
, : , , ,
, onclick,
.
, , 10.16.
10.16. JavaScript
var undeStart = "<span class='spanMatchText'>";
var undeEnd = "</span>";
var selectSpanStart = "<span style=lwidth: 100%,-display:block; '
class='spanNormalElement' onmouseover=SetHighColor(this)' ";
var selectSpanEnd ="</span>";
function CreateUnderline(xStr,xTextMatch,xVal){
selectSpanMid = "onclick='SetText(" + xVal + " ) ' " +
"id='OptionsList_"+countForId+ "'theArrayNumber='"+ xVal +'">";
var regExp = new RegExp{theTextBox.obj.regExAny +
xTextMatch,theTextBox.obj.regExFlags);
var aStart = xStr.search(regExp);
var matchedText = xStr.substring(aStart,
aStart + xTextMatch.length);
countForId++;
return selectSpanStart + selectSpanMid +
xStr.replace(regExp,undeStart +
matchedText + undeEnd) + selectSpanEnd;

406

IV. Ajax

10.16 , , CSS , .
: . , undestart, span; , undeEnd, .
.
,
. , ! , selectSpanStart
louseover. selectSpanEnd span.
CreateUnderline() MakeMatches<), . MakeMatches () :
, , ,
. , onclick .
n c l i c k , DOM .
, ,
. .
[ , , ^ search. , , . countForld 1, , span. , CSS, span.
span CSS,
3 JavaScript,
.
, CSS.
span.spanMatchText{ text-decoration: underline;
font-weight: bold; }
span.spanNormalElement{ background: #C0COCO; }
span.spanHighElement{ background: #000040;
color: white; cursor: pointer; }
span.noMatchData{ font-weight: bold; color: #0000FF; }
(. . 10.4), ,
, . CSS span.spanMatchText. (
) span. spanNormalElement.
CSS span.spanHighElement. ,
- , . ,
, ,
. : , , .. , -

10

407


. <Enter> ,
.

, , selectedlndex -
, .
1 (" ") -1 (" ").
CSS span. , currentValueSelected, . MoveHighl i g h t ( ) , 10.17, , , .
:

10.17. CSS JavaScript


function MoveHighlight(xDir){
if (currentValueSelected >= 0){
newValue = parselnt(currentValueSelected) + parselnt{xDir);
if(newValue > -1 && newValue < countForld){
CurrentValueSelected = newValue;
SetHighColor (null);

}
}
function SetHighColor(theTextBox){
if(theTextBox){
currentValueSelected =
theTextBox.id.slice(theTextBox.id.indexOf("_")+1,
theTextBox.id.length);
}
for{i = 0; i < countForld; i++){
document.getElementById('OptionsList_' + i).className =
1
spanNormalElement';
}
document. getElementByld ( ' OptionsList__' +
currentValueSelected).className = 'spanHighElement';
_}

MoveHighlight t) . , xDir, , . ,
. ,
.
currentValueSelected , SetHighColor (), .

IV. Ajax

408

SetHighColor() : ( onmouseover).

. onmouseover (. 10.16) ; ,
. ,
moveHighlight () currentValueSelected.
span CSS spanNormalElement.
. ,
CSS . ,

.
.

, ,
, , .
.
HTML select, , 10.18.
10.18.
function SetText(xVal){
theTextBox.value = arrOptions[xVal][0]; //set text value
theTextBox.obj .hidden, value arrOptions [xVal] [1] ;
document.getElementByldf"spanOutput").style.display = "none";
currentValueSelected = - 1 ; //remove the selected index
}
function GrabHighlighted(){
if(currentValueSelected >= 0){
xVal = document.getElementByldf"OptionsList_" +
currentValueSelected).getAttribute("theArrayNumber");
SetTextfxVal);
HideTheBoxO ;
}
}
function HideTheBoxf){
document.getElementByldf"spanOutput").style.display = "none";
currentValueSelected = -1;
EraseTimeout();

_J

10

409

GrabHighlighted() . , , . ,
arrOptions, . theArrayNumber,
SetText (), .
SetText () ,
arrOptions. .
,
. , , HideTheBox ().
HideTheBox () spanOutput .
s t y l e .display none. currentValueSelected - 1 .
EraseTimeout(),
.
JavaScript
, JavaScript.
, ,
. , , 10.19, ,
. , . JavaScript setTimeout(), .
, 10.6. , setTimeout ()
, useTimeout t r u e .
10.19. :
function EraseTimeout(){
clearTimeout(isTiming); isTiming false;
}
function StartTimeout{){
isTiming = setTimeout("HideTheBox()",
theTextBox.obj.theVisibleTime);

StartTimeout () . isTiming setTimeout. setTimeout HideTheBox () ,


theVisibleTime.

410

IV. Ajax

. 10.5.

, ,
. EraseTimeout (),
JavaScript clearTimeout () HideTheBox(). isTiming false.
, ! , .
,
. 10.5. (s) 15. (h) . ()
, , <Enter> , , .

10.4.

, . ,
, SetProperties (). ,
.
, , ,
SQL.

10.

, . , ,
.
if .
, -
, , . , . . ,
10.20.
10.20. TypeAhead()
function TypeAhead(xStrText){
var strParams = "q=" + xStrText + "&where=" +
theTextBox.obj.matchAnywhere + "&name=" + theTextBox.name;
var loaderl = new net.ContentLoader(theTextBox.obj.serverCode,
BuildChoices,null,"POST",strParams);
_}

strParams TypeAhead(), , ,
. , i f - e l s e case .
, .

10.5.
, , ,
. ,
, , .
,
Web- ( 20-30 Web-).
, , Ajax Web-,
, .
. , (. 10.2).

. , , , . , -

412

IV. Ajax

10.2.

HTML,
1
.

1

(, , ),
CSS

.
JavaScript,
.
( )

Internet Explorer Firefox

,
,

, ,

. , . ,
7 : . , 8 ( ).
, 6.
, .
, .

10.5.1. 1: TextSuggest
, . - - ,
. Rico ( h t t p : //openrico. org)
Prototype.js ( h t t p : / / p r o t o t y p e . c o n i o . n e t / ) . Rico
Ajax, , . Prototype , .
Prototype Rico.

10

413

prototype
prototype JavaScript, ,
. .
Class
Class, Prototype, c r e a t e (), ,
. c r e a t e {) , i n i t i a l i z e (). ,
, JavaScript. :
var TextSuggest = Class.create();
TextSuggest.prototype = {
//
initialize: function( pi, p2, p3 ) {

h
};
, ""
( ), i n i t i a l i z e ( ) .
.
var textSuggest = new TextSuggest(pi, p2, p 3 ) ;

extend
Prototype JavaScript
, extend(), . extend () :
, .
. . ,
TextSuggest .
bind/bindAsEventListener()
Prototype Function:
bind() bindAsEventListener().
. , :
oThis this;
this.onclick = function() { oThis.callSomeMethod() };

bind() Prototype .
t h i s . o n c l i c k = t h i s . callSomeMethod.binci( t h i s ) ;
API bindAsEventHandler() Event Internet Explorer W3C !

414

IV. Ajax

$ ""
JavaScript , ($). Prototype
DHTML-:
. ,
:
$ ( ' t e x t F i e l d ' ) . v a l u e = aNewValue;
.
1
var textField = document.getElementByldf'textField )
textField.value = aNewValue;
Rico
Rico, Prototype . , Rico. Rico , , , ,
. Ajax ,
Rico. Rico ,
Rico Ajax. Ajax Rico ,
ajaxEngine. API ajaxEngine
, , Ajax. , , :
ajaxEngine.registerRequest(
'getlnvoiceData',
'someLongGnarlyUrl.do' ) ;
ajaxEngine.registerAjaxObject( 'xyz', someObject );
URL Ajax.
, URL.
.
ajaxEngine.sendRequest('getlnvoiceData', request parameters . . . );
registerRequest () URL
, onload . URL ,
, registerAjaxObject() Ajax. , someObject
xyz, Ajax
ajaxUpdate ( ) .
, ajaxEngine, XML-

10 415

, Ajax. JavaScript,
, Rico XML.
<response> <ajax-response>. <response>, .
, , ,
Web-, ,
, . XML-
.
<j ax-response>
<response type="object" id="xyz">

. . . t h e r e s t of t h e XML response as normal . . .


</response>
<response... >
more response elements if n e e d e d . .
</response>
</ajax-response>

XML- ajaxEngine, , xyz. Ajax , xyz,


<response> ajaxUpdate().
. . ,
, .
, , . , ,
( 7 ). .

10.5.2. 2: TextSuggest

, ,
.
, . .
1.
HTML, . .
- ,
<body>. ,
HTML HTML-,
10.21.

IV. Ajax

416

10.21. HTML- TextSuggest


<html>
<head>
<script>
v a r s u g g e s t O p t i o n s = { / * d e t a i l s to come*/ };
f u n c t i o n i n j e c t S u g g e s t B e h a v i o r ( ) { // <head>
s u g g e s t = new T e x t S u g g e s t (
1
fieldl', 'typeAheadData.aspx', suggestOptions );
} >;
</script>
</head>
<body o n l o a d = " i n j e c t S u g g e s t B e h a v i o r ( ) " >
<form n a m e = " F o r m l " >
A u t o C o m p l e t e T e x t Box:
<input t y p e = " t e x t " id"fieldl" name="txtUserInput"> _ </form>
</body>
</html>

HTML- ,
,
, URL Ajax , . ( , .) ,
<body>, . , . TextSuggest -, ( )
Clas s. c r e a t e {) Prototype,
10.22.
10.22. TextSuggest
TextSuggest = Class.create();
TextSuggest.prototype = { initialize:
function{anld, url,
options) {//
this.id = anld;
this.textlnput = $(this.id);
var browser = navigator.userAgent.toLowerCase();
//
this.isIE =
browser.indexOff"msie") != -1;
this-isOpera =
browser.indexOf{"opera")!= -1;
//
this.suggestions = [];
this.setOptions(options);
this.initAjax(url);
this.inj ectSuggestBehavior();

11

10.

417

. , , . ,
DOM . , ,
.
Internet Explorer Opera,
.
Ajax . ( )
. , Setproperties (), .
function SetProperties
(xElem, xHidden, xserverCode,
xignoreCase, xmatchAnywhere,
xmatchTextBoxWidth, xshowNoMatchMessage,
xnoMatchingDataMessage, xuseTimeout,
xtheVisibleTime){
}
, , API
. ,
. .
.
var suggestOptiona - { matchAnywhere : true, ignoreCase : true };
function injectSuggestBehavior() {
suggest = new TextSuggest('fieldl', ' typeAheadXML.aspx',
suggestOptions ); } ) ;
.
.
, , .
,
.
s e t o p t i o n s ( ) ,
, , .
, setOptions (),
. .
setOptions: function(options) {
this,options {
suggestDivClassName:

'suggestDiv',

IV. Ajax
suggestionClassName:
'suggestion',
matchClassName : 'match',
matchTextWidth : true,
selectionColor : ' # 9 ,
matchAnywhere : false,
ignoreCase : false,
count : 10
} . e x t e n d ( o p t i o n s | I (}) ;

, . extend ()
Prototype, , .
,
, , -!
matchAnywhere ignoreCase ( true).
. 10.3.
, , CSS HTML .
, . 10.2.
3. .
(, , ),
CSS.
5.
.
(, -J
) (, -!
CSS).
,
. ,
, Ajax.

10.5.3. 3: Ajax
, Ajax? Ajax TextSuggest
. ,
.
Ajax . ,
initAjaxf), , Ajax. .
initAjax: function(url) {
ajaxEngine.registerRequest( this.id + '_request', url );
ajaxEngine.registerAjaxObject{ this.id + '_updater', this

);},

10.

419

10.3.

g g e s t D i v C l a s s N a m e CSS d i v ,

g g e s t i o n C l a s s N a m e CSS span,

matchClassName

CSS span,
,

inatchTextwidth

, ,
d i v , ,
,

selectionColor

(
, CSS ),

matchAnywhere

, ,
,

ignoreCase

, ,

count

, registerRequest () Ajax
URL, sendRequest{). ,
, URL (
ajaxEngine), . , , , .
. t h i s
, , .
, . , i d = ' f i e l d l ' ,
' f i e l d l _ u p d a t e r ' . XML-, ,
, , .
<ajax-response>
<response type='object' id= 'fieldl^updater' >.
. . . xml-, .
</response>
</ajax-response>

420

IV. Ajax

;
aj axEngine.sendRequest{
'fieldl^request',lparaml=vall1, 'param2=val2', . . .
);

, Ajax- . , .
Ajax
, - .
onchange, ,
.
, . -
, . , ( ) ,
.
sendRequestForSuggestions () :
sendRequestForSuggestions; function() {
if ( this.handlingRequest ) {
this.pendingRequest = t r u e ; return;
}
this.handlingRequest = t r u e ;
this.callRicoAjaxEngine();

, , t h . i s . c a l l RicoAj axEngine () , . this.handlingRequest t r u e Ajax false ( ) . ,


this.pendingRequest true. , , ,
. callRicoAj axEngine {), 10.23.
10.23. a j axEngine (Rico)
callRicoAjaxEngine: function() {
//
var callParms = [];
callParms.push( this.id + '^request1);
callParms.push{ T id = < + this.id);
callParms.push( 'count=' + this.options.count);
callParms-push( 'query=' + this.lastRequestString);
callParms.push( 'match_anywhere=l + this.options.matchAnywhere);
callParms.push( 'ignore_case=' + this.options.ignoreCase);
var additionalParms = this.options.requestParameters t{ [];
for( var i=0 ; i < additionalParms.length ; i++ )
callParms.push{additionalParms[i]);

10.
// Ajax
ajaxEngine.sendRequest.apply{

ajaxEngine,

callParms

4Z1

);
m

, , JavaScript, .
ajaxEngine.sendRequest.apply( ajaxEngine, callParms);
applyO,
( ). .
Greeter,prototype.greetPeople = function(strl, str2)
{
a l e r t ( ' h e l l o ' + s t r l + 'and ' + str2)
};
, Greeter, friendlyperson, greetPeople{). ,
people. apply.
:
var people = [ "Joe", "Sally" ];
friendlyPerson.greetPeople.apply( friendlyPerson, people);
apply () , , , . ,
friendlyPerson.greetPeople( people[0], people[1));
. sendRequest ()
ajaxEngine,
key=value, .
, , . .
//
var callParms - [ ] ;
callParms.push( t h i s . i d +

'^request' );

callParms.push( 'ignore_case=' + this.options.ignoreCase) ;


//
var additionalParms = this.options.requestParameters || [ ] ;
for( v a r i=0 ; i < a d d i t i o n a l P a r m s . l e n g t h ; i++ )
callParms.push(additionalParms[i]) ;

, sendRequest ()
apply, : , , l a s t Reques t s t rin g, options (, count, matchAnywhere, ignoreCase) .

,
. ^
t i o n s , requestParameters. null,
key=value. callParms,
. , .
ajaxEngine.sendRequest.apply{ ajaxEngine, callParms);
! . ,
, .
, , .
Ajax
,
, , . ,
ajaxEngine (Rico)
ajaxUpdatet), <response>. ,
a j axUpdate ( ) , . ajaxUpdateO 10.24
createSuggestionsO
getElementContent().

10.24. Ajax j M H H B H H H H H H B H ^ I
ajaxUpdate: function( ajaxResponse ) {
//
this.createSuggestions( ajaxResponse );
if ( this.suggestions.length == 0 ) {
this.hideSuggestions{);
S( this.id + "_hidden").value = "";
}
//
else {
this.updateSuggestionsDiv{);
this.showSuggestions();
this.updateSelection(0);
}
//
this.handlingRequest = false;
if ( this.pendingRequest ) {
this.pendingRequest = false;
this-lastRequestString = this.textlnput.value;
//
this.sendRequestForSuggestions();
}
},
createSuggestions: function(ajaxResponse) {
this.suggestions * [];
var entries ~ ajaxResponse.getElementsByTagNamef'entry');
for ( var i = 0 ; i < entries.length ; i++ ) {

10.

423

var strText = this.getElementContent(


entries[i1.getElementsByTagName('text') [ 0 ] );
var strValue = this.getElementContent{
entries[i].getElementsByTagName('value')[0]) ;
this.suggestions.push({ text: strText, value: strValue });
}
),
getElementContent: function(element) {
return element.firstChild.data;
_ J

Ajax, , . ,
createSuggestions (), , suggestions.
, ( <text> <value> <entry> XML-).
, ajaxUpdate(), . , , ,
, . , , , .
,
this.handlingRequest false. , ajaxUpdatet) , . , pendingRequest false, l a s tRequestString
sendRequestForSuggestions() .
, / Ajax. :
, " Ajax" ( 7),
( 2 3). , , .
.

10.5.4. 4:
, Ajax , , . , ,
, ,

424

IV. Aiax

injectSuggestBehavior{).
DOM , , , . *:
, HTML- (. 1)
10.25.
10.25.
injectSuggestBehavior: function() {
if ( t h i s . i s I E ) {
/ / I n t e r n e t E x p l o r e r
t h i s . t e x t l n p u t , a u t o c o m p l e t e = "off";
}
v a r JceyEventHandler =
new T e x t S u g g e s t K e y H a n d l e r ( t h i s ) ;
//
new I n s e r t i o n . A f t e r ( t h i s . t e x t l n p u t ,
'<input type="text" i d - " ' + t h i s . i d +
'_preventtsubmit'+
'" style="display:none"/>' );
new I n s e r t i o n . A f t e r ( t h i s . t e x t l n p u t ,
'<input t y p e = " h i d d e n " name="'+
this.id+'_hidden'+
1Tr
i d = ' " + t h i s . i d + l _ h i d d e n r + " ' / > ' );
this.createSuggestionsDivf);
/ /
},

, Internet Explorer.
, autocomplete
off.
. TextSuggestKeyHandler, . , , , . . ,
, <Enter>.
HTML-, " "
I n s e r t i o n . A f t e r ( ) .
I n s e r t i o n . After () Prototype. , createSuggestionsDiv(), div, .
TextSuggestKeyHandler
, . , . -

10.

4*

01 ,
1( MVC
, 13 , RSS-
, MVC.
, , C l a s s . c r e a t e ( ) i n i t i a l i z e ( ) . TextSuggestKeyHandler 10.26.
10.26. TextSuggestKeyHandler
TextSuggestKeyHandler = C l a s s . c r e a t e ( ) ;
TextSuggestKeyHandler.prototype = {
i n i t i a l i z e : function( textSuggest ) {
this.textSuggest = textSuggest;
t h i s . i n p u t = this.textSuggest.textlnput;

// T e x t S u g g e s t
this.addKeyHandling();
h
// API
_

, "" HTML-.
this.addKeyHandlingO . addKeyHandling() 10.27.
10.27.
addKeyHandling: function() {
this.input.onkeyup =
this.keyupHandler.bindAsEventListener(this);
this.input.onkeydown =
this.keydownHandler.bindAsEventListener(this);
this.input.onblur =
this.onblurHandler.bindAsEventListener(this);
if ( this.isOpera )
this.input,onkeypress =
this.keyupHandler.bindAsEventListener(this);

, , Opera, . , bindAsEve n t L i s t e n e r ( ) , Prototype. Internet Explorer W3C. .


keyupHandlerO, keydownHandler(), onblurHandler ()
( ).

. > keydownHandler(), 10.28, ,


.

keydownHandler: function(e) {
var upArrow = 38;
var downArrow = 4 0 ;
if ( e.keyCode =- upArrow ) {
this.textSuggest.moveSelectionUp();
setTimeout( this.moveCaretToEnd.bind(this), 1 );
}
else if ( e.keyCode == downArrow ) {
this.textSuggest.moveSelectionDown();
}


.
TextSuggest , onkeydown, onkeyup.
.
, , . , keydownHandler (). , TextSuggest.
, t h i s . textSuggest. 10.29
.
10.29. TextSuggest,
raoveSelectionUp: function{)
{
if ( t h i s . s e l e c t e d l n d e x > 0 ) {
this.updateSelection(this.selectedlndex
}

1);

moveSelectionDown: function() {
if ( this.selectedlndex < (this.suggestions.length - 1) ) {
this.updateSelection<this.selectedlndex + 1 ) ;
}

updateSelection: function(n) {
var span = $(this.id + "_"+this.selectedlndex);
if (span){
span.style.backgroundColor = "";
//
}
this.selectedlndex = n;
var span = 5(this.id+"_"+this.selectedlndex);
if (span){

span.style.backgroundColor =
this,options.selectionColor;
}

u p d a t e S e l e c t i o n ( ) . span,
(
), style.backgroundColor , o p t i o n s . s e l e c t i o n C o l o r Configuration .
,
. , ,

. moveCaretToEndt), ( setTimeout).
moveCaretToEndt) 10.30.
10.30. moveCaretToEnd () TextSuggest ' 9 |
moveCaretToEnd: function() {

v a r = t h i s . i n p u t . v a l u e . l e n g t h ;
if ( t h i s . i n p u t . s e t S e l e c t i o n R a n g e ) {
this.input.setSelectionRange(pos,pos);
}
else if(this.input.createTextRange){
var m = this.input.createTextRange{);
m.moveStart('character1, pos);
ra.collapse();
m.select();
}

. , . , ,
, .
, 10.31.
10.31. TextSuggest
keyupHandler: function(e) {
if ( this.input.length == 0 && !this.isOpera )
this.textSuggest.hideSuggestions();
if ( 'this.handledSpecialKeys(e) )
this.textSuggest.handleTextlnput() ;

handledSpecialKeys: function(e) {
var enterKey = 13;
var upArrow = 38;
var downArrow 40;
if ( e.keyCode == upArrow II e.keyCode == downArrow ) {

return true;

else if ( e.keyCode == enterKey ) {


this.textSuggest.setInputFromSelection{);
return true;
}
return false;
_

,
. , TextSuggest . ,
: ,
<Enter>. , , .
<Enter>, TextSuggest .
, , TextSuggest
, textsugcrest.handleTextInput(). TextSuggest
Ajax, .
handleText!nput() 10.32.

;' 10.32. ";. >


handleTextlnput: function{) {
var previousRequest =
this.lastRequestString;
//
this.lastRequestString =
this.textInput.value;
//
if { t h i s . l a s t R e q u e s t S t r i n g == "" )
this.hideSuggestions();
e l s e if ( t h i s . l a s t R e q u e s t S t r i n g != p r e v i o u s R e q u e s t )
this.sendRequestForSuggestions();
// Ajax
}

handleTextlnput
previousRequest t h i s . l a s t RequestString. lastRequestS t r i n g , ,

, .
, .
, handleTextlnput () -

10.

429

sendRequestForSuggestions() ( )
Ajax . ,
. , - . , ,
Ajax, ,
, .
!
onblur, , . :

onblurHandler: function(e) {
if ( this.textSuggest.suggestionsDiv.style.display == " )
this.textSuggest.setlnputFromSelection();
this.textSuggest.hideSuggestions();
}

onblurHandler handledspecialKeys TextSuggest, , s e t l n p u t FromSelection ( ). , , SetText () ;


, ;
. .
setlnputFromSelection: function() {
var hiddenlnput $( this.id + "_hidden" );
var suggestion ~ this.suggestions[ this.selectedlndex ];
this.textlnput.value = suggestion.text;
//
hiddenlnput.value = suggestion.value;
//
this.hideSuggestions();
}

, , ,
.
c o n t r o l l e r , , . Internet Explorer W3C bindAsEventListener()
Prototype. /
,
. , ; ; DOM ,
<Enter>. , TextSuggest. , ,

430

IV Ajax

, ,
, . .

10.5.5. 5:

, ,
.
, Ajax, , .
. .
. div
span .
.
.
.

injectSuggestBehavior (). ,
DOM, TextSuggest.
injectSuggestBehavior: function{) {
// DOM HTML . . .
this.createSuggestionsDiv();

injectSuggestBehavior() createSuggestionsDiv(), div


. GUI, .
10.33.
10.33.
createSuggestionsDiv: function{) {
this.suggestionsDiv = document.createElement("div");
// div
this.suggestionsDiv.className
this.options.suggestDivClassName;
// div
var divStyle = this.suggestionsDiv.style;
//
divStyle.position = 'absolute1;
divStyle.zlndex = 101;
divStyle.display - "none";

10
/ /
this.textlnput.parentNode.appendChild

431

(this.suggestionsDiv);

, . div API createElement () .


div . ,
, CSS . className div suggestDivClassName . ( setOptions) suggestDiv. , , . ,

TextSuggest, . , (,
),
. , suggestDivClassName
, . .
,
,
, s t y l e .
, ,
style, , CSS
className ( ). .
p o s i t i o n = ' a b s o l u t e ' ( div).
zlndex=10l ( ).
display="none" (
, ).
, 101 zlndex . , div
.
, div .

, , -

,
. positionSuggestionsDiv, , 10.34.
10.34.
positionSuggestionsDiv: function!) {
var textPos = RicoUtil.toDocumentPosition{this.textlnput);
var divStyle = this.suggestionsDiv.style;
divStyle.top = (textPos.y + this.textlnput.offsetHeight)
+ "px";
divStyle.left = textPos.x + "px";
if ( this.options.matchTextWidth )
divStyle.width = (this.textlnput.offsetWidth
this.padding()) + "px";

,
.
toDocumentPosition(). , , ,
, .
matchTextWidth, t r u e , div
. , . ,
div CSS. ,
, , .
padding() ( 10.35), , .
10,35. [
padding: function() {
try{
var styleFunc = RicoUtil.getElementsComputedStyle;
var lPad = styleFunc( this.suggestionsDiv,
"paddingLeft",
"padding-left" );
var rPad = styleFunc( this.suggestionsDiv,
"paddingRight",
"padding-right" );
var lBorder = styleFunc( this.suggestionsDiv,
"borderLeftwidth",
"border-left-width" );
var rBorder = styleFunc( this.suggestionsDiv,
"borderRightWidth",
"border-right-width" ) ;
lPad = isNaN(lPad) ? 0 : lPad;
rPad = isNaN(rPad) ? 0 : rPad;
lBorder = isNaN(lBorder) ? 0 : lBorder;

rBorder isNaN(rBorder) ? 0 : rBorder;


return parselnt(lPad) + parselnt(rPad) +
parselnt(lBorder) + parselnt(rBorder);
}catch (e){ return 0; }

__K

(
, , ),
. Internet Explorer c u r r e n t s t y l e , Mozilla getComputedStyle () defaultview .
. c u r r e n t s t y l e (Internet Explorer) ,
JavaScript (, borderRightWidth), getComputedStyle() (Mozilla) ,
(, b o r d e r - r i g h t width). , Rico , , RicoUtil.getElementsComputedStyle().
, Internet Explorer Mozilla,
.
, .
Rico.getElementsComputedstyle() Safari,
t r y . . .catch.

, , .
, . , ajaxUpdateO
XML-, -.
, ,
t h i s .updateSugggestionsDiv().
span
( div). , .
updateSuggestionsDiv: function() {
this.suggestionsDiv.innerHTML = "";
//
v a r s u g g e s t L i n e s > t h i s , c r e a t e S u g g e s t i o n S p a n s ( ) ;
//
f o r ( v a r i = 0; i < s u g g e s t L i n e s . l e n g t h ; i + + )
this.suggestionsDiv.appendChild(suggestLines[i]);
),


. innerHTML suggestionsDiv, ( ). c r e a t e SuggestionSpans (), span

434

IV. Ajax

. ,
div. . createSuggestionSpans (),
10.36, , -.
10,36.
createSuggestionSpans: function() {
var regExpFlags "";
if { this.options.ignoreCase )
regExpFlags - 'i r ;
var startRegExp = " ";
if { this.options.matchAnywhere )
StartRegExp = ' ';
var regExp new RegExp( startRegExp +
this.lastRequestString,
regExpFlags );
var suggestionSpans = [};
for ( var i = 0 ; i < this.suggestions.length ; i++ )
suggestionSpans.push(
this.createSuggestionSpan( i, regExp ) );
return suggestionSpans;


ignoreCase matchAnywhere. ,
, , . suggestions
( , .text .value). createSuggestionSpan() .
, createSuggestionSpan(),
10.37.
10.37.
createSuggestionSpan: function( n, regExp ) {
var suggestion = this.suggestions[nj;
var suggestionSpan = document.createElement("span");
suggestionSpan.className = this.options.suggestionClassName;
suggestionSpan. style, width =* '100%';
1
suggestionSpan.style.display = 'block ;
suggestionSpan. id = this.id + "__" + n;
suggestionSpan.onmouseover =
this.mouseoverHandler.bindAsEventListener(this);
suggestionSpan.onclick =
this.itemClickHandler.bindAsEventListener(this);
var textValues - this.splitTextValues( suggestion.text,
this.lastRequestString.length,
regExp );
var textMatchSpan = document.createElement("span");
textMatchSpan.id - this.id + "_match_" + n;

10

435

textMatchSpan.className = this.options.matchClassName;
textMatchSpan.onmouseover =
this.mouseoverHandler.bindAsEventListener(this);
textMatchSpan.onclick =
this.itemClickHandler.bindAsEventListener(this);
textMatchSpan.appendChild(
document.createTextNode(textValues.mid) );
suggestionSpan.appendChild(
document.createTextNode(textValues.start) );
suggestionSpan.appendChild(textMatchSpan);
suggestionSpan.appendChild(
document.createTextNode(textValues.end) );
return suggestionSpan;

, . , , , ,
. ,
: HTML- .
HTML- , :
<span>before <span>
matching text
</span>, and after</span>

,
. , "matching text",
"before matching text, and after".
, ,
, span , , .

:
var textValues = this.splitTextValues(
suggestion.text, this.lastReguestString.length, regExp );

textValues ,
: .start, .mid .end. ,
textValues , :
textValues = { start: 'before ',
mid: 'matching text',
end: ', and after1 };

, splitTextValues ().
splitTextValues: function{ text, len, regExp ) {
var startPos = text.search(regExp);
var matchText = text.substring( startPos, startPos + len );
var startText = startPos == 0 ?
"" : text.substring(O, startPos);
var endText = text.substring( startPos + len );
return { start: startText, mid: matchText, end: endText };

IV. Ajax

436

, , . CSS suggestionClassName matchClassName Options .


CSS suggestionsDiv
HTML- .
, ,
, . mouseover; , , . ,
onclick,
.
10.38.
10.38,
mouseoverHandler: function(e) {
var src = e.srcElement ? e.srcElement : e.target;
var index = parselnt (src. id. substring(src.id.lastIndexOf ('__')+l));
this.updateSelection(index);

itemClickHandler: function(e) {
this.mouseoverHandler(e);
this.hideSuggestions() ;
this.textlnput.focus();

mouseoverHandler () , . updateSelection(},
, ,
.
itemClickHandler () , mouseoverHandler(). itemClickHandler() , hideSuggest i o n s () , .
, .
.

,
, , . ,

10.

437

, DHTML-.
display . . 10.39, .
10.39,
showSuggestions: function() {
var divStyle = this.suggestionsDiv.style;
if ( divStyle.display == " )
return;
this.positionSuggestionsDiv();
//
divStyle.display = ";
//
>.
//
hideSuggestions: function() {
this.suggestionsDiv.style.display =
' none';

s t y l e . d i s p l a y
suggestionsDiv, ( ,
) ( ) . showSuggest i o n s ()
. ! ! . .

10.5.6.
, .
,
. TextSuggest ; ; ; , ,
API... , , . 10.2. http://www.manning.com/crane (http://www.dialektika.com/);
Rico h t t p : / / o p e n r i c o . o r g / , Prototype
h t t p : / / p r o t o t y p e . c o n i o . n e t / .

10.6.
, , , ,
. , ,
. -

438

IV. Ajax

,
.
,
DHTML. , Ajax Web-. ,
, Ajax,
, (
). ,
- JavaScript, TextSuggest.

Ajax



.

440

IV Ajax


.

Web-, . ,
Yahoo!, , , , , . Amazon
A9.com,

Web-, , . 9. com Ajax. , ,
.
Ajax ,
. "" .. , ,
. , .
, . , . , , , Ajax .

11.1.
,
, ,
. :
, , , ..
, , ,
.

11.1.1.
(
).
, .

. 11.1. Yahoo!


. ,
, . ,
. , , , ,
.
Yahoo!. Yahoo!,
, , , . . 11.1, Yahoo! .
Yahoo! , .
, . . 11.1, ,
(). , , Ajax .
Amazon A9.com.

. 11.2. A9.com Web

11.1.2.
Ajax , , , .

. Amazon A9.com. , .
. 11.2
Web.
. , , Books. Book Results. 11.3,

.
Ajax
. Ajax

Web, ,
. , .
, Ajax,
, .

. 11.3. A9.com B o o k R e s u l t s

11.2. Java
Ajax
, , . ,
Ajax, , , , .
, (, ). ,
. ,
(. 11.4).

, Ajax, , , .
, . 11.4, : . , Ajax
.
, ,
DHTML .

DHTML. , IFrame .

. 11.4- Ajax
.

. 115.
u s e r s SQL Squirrel

. 11.6. u s e r s

11.3.1.
, , users,
, . , id, username
password, SQL-, 11.1. . 11.5
SQL Squirrel ( h t t p : / / s q u i r r e l - s q l . s o u r c e f o r g e . n e t ) .
11.1. users
create table users(
id int primary key unique not null,
username varchar(50) not null,
password varchar(50) not null

>;

.
.
. 11.6, 1 2. .
, . ,
, . Ajax ,
.

446 IV. Ajax

, , . ,
. ,
SQL.
, users,
, .

11.3.2. : Java
Ajax , ,
.
, .
. , , . , ,
, . ,
. , .
Java,
.
, : ,
.
7. , , , , , ,
. 11.2.
>,

11.2. L o g i n F i i t e r . j ava:

public class LoginFiiter implements Filter {


public void initfFilterConfig config)
throws ServletException { }
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain filterChain)
throws lOException, ServletException {
boolean accept=false;
HttpSession session=(
(HttpServletRequest)request).getSession();
User user=(User)
(session.getAttribute("user"));
// User
if (user==null){
accept=login(request);
//
}else{
accept=true;

11. Web- Ajax

447

//
}
if (accept){
filterChain.doFilter
(request,response);
//
}else(
Writer writer=response.getWriter();
writer .write
.. .
(JSUtil.getLoginError()) ;
//
writer,flush() ;
writer.closet);
}

//

//

//

//

>

}
private boolean login(ServletRequest request){
0
String user=request.getParameter("username");
String password=request.getParameter("password");
User userObj=findUser(user,password);
if (userObj!=null){
HttpSession session=
((HttpServletRequest)request).getSession(true) ;

session.setAttribute("user",userObj);
}
return (userObj!=null);
}
private User findUser(String user, String password) {
User userObj=null;
Connection conn=DBUtil.getConnection();
SQL
try{
String sql="SELECT id FROM users WHERE username='"
+user+"' AND password'"+password+"'";
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
if (rs.next()){
User
int id=rs.getlnt("id");
userObj=new User(id,user);
}
Icatch (SQLException sqlex){
}
return userObj;
}
public void destroyO { J

____M

, , *
User . , ;
*

, . , ;
. JavaScript
JSUtil. , .
public s t a t i c String getLoginError() {
StringBuffer jsBuf=new StringBuffer()
.append("document.getElementByldf 'spanProcessing 1 )(BBSS)n")
.append(" .innerHTML = ")
.append("'The Username and Password are invalid';(BBSS)n");
return jsBuf.toStringf);
}
login (), 11.2. ,
finduserf), . ( ,
; DBUtil.) , , ,
User ,
, ,
User .
. , , User .
11.3, User
.
If' ^ 13. User.java
public class User {
private int id=-l;
private String userName-null;
public User(int id, String userName) {
super();
this.id = id;
this.userName = userName;
}
public int getld() { return id;}
public String getUserNamef) { return userName;}

_J

. , , !
. .
,
.

11. Web- Ajax

449

11.3.3. ( )
. , . HTML- ; , div, span
CSS.
Ajax JavaScript,
.
JavaScript eval ().
JavaScript. , . eval () , . eval() ,
- .
HTML
,
.
, Ajax,
,
. ,
, .
, span,
,
. div span, HTML-, . 11.4
HTML- .
11.4. HTML-
< ! >
<form n a m e = " F o r m l " >
< i Q >
<div id="header">
< ! span >
<span id="login">
Name:
< ! >
<input type="text" name="username">
< ! >
<br>Password:
<input type="password" name="password">
<br/>
< ! span >
<span
id="spanProcessing"x/span>
<input type="button" name="btnSub" value-"login"
< ! "" >
onclick="LoginRequest() ">
</span>

. 11.7. HTML
CSS

< ! >
<span i d = " s l o g a n T e x t " > A j a x P o r t a l < / s p a n >
</div>
< ! >
<div id="defaultContent">
<p>Some t e x t g o e s h e r e ! < / p >
</div>
<div i d = " d i v S e t t i n g s " c l a s s = " h i d d e n " X / d i v >
</form>

HTML-. . ,
Ajax, .. .
div , . span ,
0, span 0 .
, , onclick. Ajax,
JavaScript LoginRequestt) ( ,
" (JavaScript)").
,
,
. div defaultContent .
, , , ,
. HTML-;
CSS . 11.7.
"" ,
CSS. , . ,
#
, <style>. <style>, . 11.5, CSS,
, , , , ..

11. Web- Ajax

451

11.5. CSS
<style

type="text/css">

< ! h t m l body >


h t m l , body{ m a r g i n : Opx; p a d d i n g : ;
height:100%; }
< ! - - >
# h e a d e r { b a c k g r o u n d - c o l o r : #C0C0C0;
h e i g h t : ;
border-bottom: lpx s o l i d black;
font-weight: bold; J
< ! s p a n >
#login{ t e x t - a l i g n : r i g h t ; f l o a t : r i g h t ;
margin-top:15px;
margin-right:15px; )
< ! - - - - >
# s l o g a n T e x t { f o n t - s i z e : 25px;
m a r g i n - l e f t : 15px;
l i n e - h e i g h t : ; }
</style>

. ( height) 100%. ,
HTML body,

.
,
div. ,
, . ,
, .
. float
r i g h t . t e x t align, span . . ,
, . ,
,

div .
. ( l i n e h e i g h t ) div,
. ,
, . ,
Ajax .
CSS ,
CSS ( 11.8).

. 11.8.
Ajax

, ,
. , HTML , . , . , JavaScript,
, .
(JavaScript)
JavaScript, , Ajax, ,
.
JavaScript n e t . j s , ContentLoader, Ajax .
<script type="text/javascript" s r c = " n e t . j s " x / s c r i p t >
ContentLoader , -3
, , ,
, 3. , - '
n e t . j s , . .
: -, ,
; -, , -, ( 11.6).
11.6. XMLHttpRequest
function LoginReguest(){
document.getElementById("spanProcessing").innerHTML =
" Verifying Credentials";
var url = 'portalLogin.servlet';
var strName = document.Forml.username.value;
var strPass = document.Forml.password.value;
var strParams = "user="+strName + "&pass=" + strPass
var loaderl = new net.ContentLoader(
url,CreateScript,null,"POST",strParams);

_ J

. 11.9. ,

,
,
.
, , .
,
, . ContentLoader, URL,
, , , , POST, , . , : CreateScript{).
function CreateScript() {
strText - this.req.responseText; eval(strText);
}
, JavaScript responseText . JavaScript,
eval (), ,
, . ,
LoginFilter, ,
S e l e c t S e r v l e t ( 11.8).
? XML-,
.
JavaScript, e v a l ( ) . ,
5, , , . ,
.
XML JSON.
, ,
. . 11.9,
.
"login" . 11.9 , , .

, , , .
. , DHTML,
,
DHTML- JavaScript.

11.4. DHTML
Ajax ,
. , ( ). Ajax
( ). , ,
, .
. DHTML-,
, ,
DHTML. , JSWindow. js,
JavaScript, . ( Web- .)
Ajax,
.

11.4.1.
, DHTML .
.

. - , ,
. portal_windows
SQL-:
create table portal_windows(
id int primary key not null, user_id int not null,
xPos int not null, yPos int not null,
width int not null, height int not null,
url varchar(255) not null, title varchar(255) not null
);

. 11.10.
portal_windows

. . user_id
. , . .
Ajax DHTML
, .
DHTML
. . , , xPos yPos. ,
DHTML: . .
URL ,
,
. , portal_windows , 11.10.
, ,
. users . . 11.10, 1 DHTML.
. 11.11 , DHTML !
, , . *
Web-: JavaRanch, Google Eric's Ajax Blog. ,
. ,

11.4.2.

,
JavaScript-, ,

. 11.11. , 1

. P o r t a l Window, ,
11.7.
11.7. PortalWindow.java
public class PortalWindow {
private
private
private
private
private
private
private
private

int id=-l;
User user=null;
int xPos=0;
int yPos=0;
int width=0;
int height=0;
String url=null;
String title=null;

public PortalWindow(
int id. User user, int xPos, int yPos,
int width,int height,
String url, String title
) {
this.id = id;
this.user = user;
this.xPos = xPos;
this.yPos = yPos;
this.width = width;
this.height = height;
this.url = url;
this.title = title;
}
public
public
public
public
public
public
public
public
public
public
public
public
public

int getHeight() {return height;}


void setHeight(int height) {this.height height;}
int getld() {return id;}
void setld(int id) {this.id = id;}
String getTitle() {return title;}
void setTitle(String title) {this.title = title;}
String getUrl() {return url;}
void setUrlfString url) {this.url = url;}
User getUser() {return user;}
void setUser(User user) {this.user = user;}
int getWidth() {return width;}
void setWidth(int width) {this.width width;}
int getXPos() {return xPos;}

public void setXPos(int pos) {xPos = pos;J


public int getYPos() {return yPos;}
public void setYPos(int pos) {yPos = pos;}
}

,
. , ,
ORM-, Hibernate
iBATIS, ,
-. , , , ,
. URL, portalLogin, servlet, ,
JavaScript.
11.8.
11.8. SelectServlet. Java
public class SelectServlet extends HttpServlet {
protected void doPost(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
HttpSession session=request.getSession();
User user={User)
//
(session.getAttributef"user"));
StringBuffer jsBuf=new StringBuffer();
if (user==null){
jsBuf.append(JSUtil.logout()) ;
}else{
List windows=DBUtil
// 0
.getPortalWindows(user);
// JSUtil
j sBuf.append(JSUtil.initUI() );
for (Iterator iter=windows.iterator();iter.hasNext();)
PortalWindow window=(PortalWindow)(iter.next());
session.setAttribute("window_"+window.getld(),window)
jsBuf.append
//
(JSUtil.initWindow(window));
}

//

>

Writer writer=response.getWriter();
0 .
writer.write(j sBuf.toString());
writer.flush();
}

IV. Ajax

458

DBUtil JSUtil JavaScript. DBUtil


getPortalWindows () , User.
, . JavaScript
( ) JSUtil.
, ,
.
0.
,
, DBUtil JSUtil. DBUtil . , ,
Hibernate ; 11.9 DBUtil,
portal_windows . SQL,
.
11.9. getPortalWindows .
public s t a t i c List getPortalWmdows (User user){
List list=new ArrayList();
Connection conn=getConnection();
try{
String sql="SELECT * FROM portal_windows "
+"WHERE user_id="+user.getld();
//

SQL
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
PortalWindow w i n = n u l l ;
while (rs.next()){
// @
int id=rs.getlnt("id") ;
int x=rs.getlnt("xPos") ;
int y=rs.getlnt("yPos");
int w=rs.getlnt("width");
int h=rs.getlnt("height");
String url=rs.getString("url");
String
title-rs.getString("title");
win=new P o r t a l W i n d o w (
//
id,user,x,y,w,h,url,title) ;
list.add(win); }
rs .close();
strat.close();
}catch (SQLException s q l e x ) {
}
return list;
}

11. Web- Ajax

459

, SQL ,

PortalWindow .
JSUtil,
JavaScript.
, .
.
public s t a t i c String initwindow(PortalWindow window) {
StringBuEfer jsBuf=new StringBuffer{)
.append("CreateWindow{new NewWin('")
.append(window.getId())
.append("',")
,append(window.getXPos())
.append(",")

.append(window.getYPos())
.append(",")
.append(window.getWidth())
.append(",")
.append(window.getHeight())
.append(",'")
.append(window.getUrK))
.append("','")
.append(window.getTitle{))
. a p p e n d ^ " ) ) ; (BBSS)n 11 );
return
jsBuf.toString();

initwindow () JavaScript
. JavaScript , :
initwindow () ( ):
document.getElementByld('login' )
.innerHTML='Welcome back!'
document.getElementByld('defaultConten')
.style.display=tquotenonetquote;
CreateWindow(
new NewWin(
tquoteltquote,612,115,615,260,
tquotehttp://www.j avaranch.comtquote,tquoteJavaRanchtquote
)
);
CreateWindow(
new NewWin(
tquote2tquote,10,115,583,260,
tquotehttp://www.google.comtquote,tquoteGoogletquote
)
>;
CreateWindow(
new NewWin(

460

IV. Ajax
tquote3tquote,10,387,1220,300,
tquotehttp://radio.j avaranch.com/pascarellotquote,
tquoteAjax Blog!tquote
)

>;

,
"" ; . , , . display
DOM defaultContent ,
.
JavaScript . CreateWindow(),
JavaScript. . , . JavaScript,
, OKHaid, width, height, xPos, yPos, url
t i t l e . , JavaScript eval ()
.
, , , ,
JavaScript. ,
, .
JavaScript
JavaScript. , .

11.4.3. JavaScript
, DHTML, Web- www.manning.com. JSWindow. js
DOM JavaScript, .
, ,
.
, .
, . JavaScript A j axWindow. j s .
, AjaxWindow. js, JavaScript s c r i p t .
JavaScript element src.
s c r i p t , . j s , HTML-.
<script type="text/javascript" src="AjaxWindow.js"X/script>

. 11.12. Ajax

, DHTML,
.
AjaxWindow.css Web- www.manning.com ( www.dialektika.com)
, l i n k href.
<link rel="stylesheet" type="text/css"
href="AjaxWindows. c s s " x / l i n k >
, HTML- JavaScript CSS, , . ,
,
JavaScript. ,
, , , 11.12. ,

. , , , .
, ,
DHTML ( Ajax
). ,
.
.
.
w DHTML .

. 11.13. Ajax

,
,
.
, .
.
,
. 11.13 , . 11.12.

; . j s. , Ajax
.

11.5.
Ajax , (
). , .
onmouseup,
.
onmouseup , ,
. Ajax, .

11 Web- Ajax

463

11.5.1.
, DHTML JavaScript
, , . JavaScript-
AjaxWindow.js, ( , ). , ,
, .
, , ,
. ,
.
Ajax.
DHTML Ajax
DHTML, , DOM
.
. ,
, onmouseup AjaxWindow.js. ,
.
document.onmouseup = function(){
bDrag = false;
bResize = false;
intLastX = - 1 ;
document.body.style.cursor = "default";
elemWin="";
bHasMoved = false;
}
false,
.
. , elemWin.
, XMLHttpRequest .

, . onmouseup , .
document.onmouseup = function(){
bDrag = false;
bResize - false;
intLastX * - 1 ;
document.body.style.cursor - "default";
if(elemWm && bHasMoved)SaveWindowProperties(elemWin);
bHasMoved = false;
}

IV. Ajax

464

,
. ,
. , SaveWindowProperties ()
.

,
. DHTML CSS. ,
, . , CSS,
, . , Ajax
( 11.10).
;;11:10,; Sa&ff&SowPropertiesO
function SaveWindowProperties(){
winProps - "ref=" +
elemWin.id;

' ^ /

/ /
w i n P r o p s + "&=" +
//
parselnt(elemWin.style.left);
//
w i n P r o p s += "&=" +
parselnt(elemWin.style.top);
w i n P r o p s += "&w=" +
parselnt{elemWin.style.width);
w i n P r o p s += "&h=" +
parselnt(elemWin.style.height);
// S e t t i n g s
Settings("saveSettings",winProps);
elemWin = " " ;
//

_J

11.11, , .
. win id (
JavaScript ).

l e f t top . ,
, width
height.

11. Web- Ajax

465

, Settings () (
) . ,
elemWin , . elemWin ,
. SaveWindowPropert i e s (), Ajax JavaScript Settings ().

11.5.2.
Ajax ,
. , . ,
, (. 10), ( ). ,
,
. ,
, . ,
XMLHttpRequest, . , .
:
XMLHttpRequest . , ,
. , XMLHttpRequest.
function Settings(xAction,xPararas){
var u r l e xAction + " . s e r v l e t " ;
var strParams = xParams;
var loader! - new net.ContentLoader(url,
BuildSettings,
ErrorBuildSettings,
"POST",
strParams);
}
Settings () . , .
, . , BuildSettings ( ) .
- , ErrorBuildSettings ().
function BuildSettings(){
strText = this.req.responseText;
document.getElementById("divSettings").innerHTML = strText;
}
function ErrorBuildSettings(){
alert(tquoteThere was an error trying to connect

466

IV Aiax
to the server.tquote);
document.getElementByld("divSettings").style.display = "none";

}
BuildSettings ()
XMLHttpRequest, .
, ,
. ,
. , , , .
6.

. , .
:
, , , .
XMLHttpRequest,
onmouseup.
SQL, , , . UpdateServlet,
11.11.

11.11. Upda^erviet. ^
public class UpdateServlet extends HttpServlet {
protected void doPost{
HttpServletRequest request,
HttpServletResponse response
)throws ServletException, IOExceptionf
String windowld*
//
request.getParameter("ref");
HttpSession s e s s i o n = r e q u e s t . g e t S e s s i o n ( ) ;
PortalWindow window=(PortalWindow)

// Window
(session.getAttribute
{"window_"+windowld));
window.setXPos(getlntParamfrequest,"x"));
window.setYPos(getlntParamfrequest,"y"));
window,setWidth(getIntParam(request,"w")) ;
window.setHeight(getIntParam(request,"h"));
//
DBUtil.savePortalWindow(window);
Writer w r i t e r = r e s p o n s e . g e t W r i t e r ( ) ;
//
w r i t e r . w r i t e ( " S a v e Complete");
writer.flush();
J
p r i v a t e i n t get!ntParam(HttpServletRequest r e q u e s t ,

11 Web- Ajax

467

String param) {
String str=request.getParameter(param) ;
int result=Integer.parselnt(str);
return result;
}
_}

, PortalWindow ,
. DBUtil
, . , , 11.12, ,
.
public s t a t i c void savePortalWindow(PortalWindow window){
Connection conn=getConnection();
i n t x=window.getXPos();
i n t y=window.getVPos();
i n t w=window.getWidth{);
i n t h=window.getHeight();
i n t id=window.getld();
String sql="UPDATE portal_windows SET xPos="+x
+", yPos="-t-y
+",width="+w
+",height="+h
+" WHERE id="+id;
try{

>

Statement stmt=conn.createStatement();
stmt.execute(sql);
stmt.close() ;
}catch (SQLException s q l e x ) {
}
m

, 11.12, .
PortalWindow SQL.
JavaScript-, .
,
. , , . , . ( ) ,
, . . , , .

468

IV. Ajax

,
, , Web- .
, , , , . -
. ,
-, , , , . - , , ,
www.manning.com.
, ,
. , , ,
, .

11.6.
, Ajax ,
, .
, ,
, . , , .
, -
, HTML- ( ).
, , .
Java, ( , ). ,

. Web- Java
URL; web.xml,
Web- (.war). , Sel e c t S e r v l e t , , ,
URL p o r t a l L o g i n . s e r v l e t .
Ajax . Java, Java, URL. -

]
',
]
]
]
]

11. Web- Ajax

469

, ( ASP.NET) , , ( : GET POST). , tion=login&userid=userspassword=password. Java, ,


URL, . p o r t a l , , URL, l o g i n . p o r t a l .
,
, , Java. ,
, ,
, . ,
.
HTML- , . , HTML-
,
.
<input type="button" name="btnSub" value="login"
onclick="LoginRequest(tquotelogintquote)">
onclick, ,
-. ,
, . , ,
11.13.
11.13.
function createPortal() {
myPortal = new Portal(
/ / URL
tquoteportalManagertquote,
{
//
messageSpanld: tquotespanprocessingtquote,
urlSuffix: tquote.portaltquote }) ;
//
myPortal.loadPage(Portal-LOAD_SETTINGS_ACTION);
document.getElementById(tquoteusernametquote).focus{) ;
}
function login() {
myPortal.login(document.getElementByld(tquoteusernametquote).value,
document.getElementById(tquotepasswordtquote).value);

470

IV. Ajax

c r e a t e p o r t a l (),
, . URL , , 0.
DOM, , ,
. API loadPage,
, . , , .
login () , login {) , .
onclick login () .
<input type="button" name="btnSub" value="login" onclick="login()">

11.6.1.
, . .
function Portal( baseUrl, options ) {
this.basellrl = baseUrl;
t h i s . o p t i o n s - options;
this.initDocumentMouseHandler();
URL
Ajax , , . ,

, . ,
, portalManager (. 11.13).
, ,
, :
myPortal = new Portal(
tguotedatatquote,
{ messageSpanld: tquotespanProcessingtquote,
urlSuffix: tquote.phptquote }

);
, URL "" ,
actionParam, URL
.php, URL, dat a / l o g i n , php. ,
. URL 11.6.3. . , -

11. Web- Ajax

471

AjaxWindows.js.

11.6.2. AjaxWindows.js
, AjaxWindows.js
. , , Ajax ,
mouseup.
, . ,
, AjaxWindows.js
, mouseup. AjaxWindow.js , . , .. ,
,
. ,
.
,
"". , - . ,
:
t h i s . initDocumentMouseHandler();
initDocumentMouseHandler () AjaxWindows.js. , ,
document.onmouseup,
. , handleMouseUp(), ( 11.14).
11.14. AjaxWindows.js
initDocumentMouseHandler: function() {
var oThis = this;
document.onmouseup = function() { oThis.handleMouseUp(); };

handleMouseUp: function() {
bDrag = false;
bResize = false;
intLastX = -1;
document.body.style.cursor = "default";
if { elemWin && bHasMoved )
this.saveWindowProperties(elemWin.id);
bHasMoved = false;

__

, .
AjaxWindows.js mouseup , -

IV. Ajax

472

,
. ,
, AjaxWindows.js. .
function ajaxWindowsMouseUpHandler() {
// logic h e r e . . .
}
document.onmouseup

ajaxWindowsMouseUpHandler;

ajaxWindowsMouseUpHandler ()
, AjaxWindows.js.
,
.
initDocumentMouseHandler: function() {
this.ajaxWindowsMouseUpHandler =
aj axWindowsMouseUpHandler;
//
var oThis = t h i s ;
d o c u m e n t . o n m o u s e u p = f u n c t i o n ( ) { o T h i s . h a n d l e M o u s e U p ( ) ; };

//
handleMouseUp: function() {
this.aj axWindowsMouseUpHandler() ;
// Ajax
if { elemWin && bHasMoved )
this.saveWindowProperties(eleraWin.id) ;
>,

handleMouseUp () AjaxWindows.js. ,
Ajax . mouseup Ajax Windows , .
. , ,
, elemWin HasMoved.
mouseup ,
-
mouseup, :
this.ajaxWindowsMouseUpHandler

this.document.onmouseup;

, , ,
,
. ,
, .. AjaxWindows.js
, mouseup. ^, ,
mouseup
, .

, , .
API . handleMouseUp (), ,
. saveWindowPrope r t i e s t ) , .
, API
.

11.6.3.
, , ,
.
Ajax . Command Ajax 3 5.
.
, : ,
. , ,
.
. , ,
,
. , .
, . :
Portal.LOGIN_ACTION "login";
Portal.LOAD__SETTINGS_ACTION - "PageLoad";
Portal.SAVE_SETTINGS_ACTION = "UpdateDragWindow";
Portal.ADD_WINDOW_ACTION - "AddWindow";
Portal.DELETE_WINDOW_ACTION - "DeleteWindow";

, , , ,
. , .
"" . ,
. , ,
(. 11.1).
,
, . , Ajax- .
.
myPortal.issuePortalCommand( Portal.SAVE_SETTINGS_ACTION,
"settingl=" + settinglValue, "setting2=" + setting2Value, . . . )-"
issuePortalCommand(), (,

11.1.

(,
PageLoad
LoadPage)


LOAD_SETTINGS_ACTION
.

) , , / . , , sendRequest()
net.ContentLoader. issuePortalCommand() :
issuePortalCommand: function{ commandName ) {

/ /
var actionParam - t h i s . o p t i o n s [ t q u o t e a c t i o n p a r a m t q u o t e ] ;
// URL
var urlSuffix = this.options[tquoteurlSuffixtquoteJ;
if ('urlSuffix)
urlSuffix="";
var u r l = this.baseUrl;
var callParms " [];
if (actionParam){ callParms.push(
//
actionParam + "=" + commandName );
}else{
// URL
url += "/" + commandName + urlSuffix; }
for ( var i = 1 ; i < arguments.length ; i++ )
callParms.push( argumentsfi] );
var ajaxHelper = new
// 0 ContentLoader
net.ContentLoader( this, url, "POST", [] );
ajaxHelper.sendRequest
// 0
,apply( ajaxHelper, callParms );
),

URL, ,
11.6.1, actionParam
, POST, . , URL ,
URL, . .
.
URL ContentLoader , , ,

. API . ""
, , , .
, .

, onclick login () ,
. login ( , ) , , , ( ) , load-page.
, login ( ) , 11.15.
login: function(userName, password) {
this.userName = userName;
this.password - password;
if ( this.options.messageSpanld )
document.getElementById(
this.options.messageSpanld).innerHTML =
"Verifying Credentials";
this.issuePortalCommand( Portal.LOGIN_ACTION,
"user=" + this.userName, "pass=" + this.password );
},

"Verifying Credentials" span,


t h i s . options .messageSpanld.
login , , .
issuePortalCommand{).

, c r e a t e P o r t a i () .
, .
issuePortalCommand{).
,
, .
loadPage: function(action) {
this.issuePortalCommand( Portal.LOAD_SETTINGS_ACTION,
"user=" + this.userName, "pass=" + this.password ); },

476

IV. Ajax


. , AjaxWindows.js mouseup .
saveWindowProperties: function(id) {
this.issuePortalCommand( 'portal.SAVE_SETTINGS_ACTION,
"ref=" + id, "x=" + parselnt(elemWin.style.left),
"y=" + parselnt(elemWin.style.top),
w=" + parselnt(elemWin.style.width),
"h=" + parselnt(elemWin.style.height) );
elemWin = n u l l ; },


( , ,
),
API, .
addWindow: f u n c t i o n ( t i t l e , u r l , , , w , h ) {
t h i s . i s s u e P o r t a l C o m m a n d ( P o r t a l .ADD__WINDOW_ACTION,
" t i t l e - " + t i t l e , " u r l - " + u r l , "x=" + x,
" y = " + y, " w = " + w, " h = " + h ) ; },
deleteWindow: f u n c t i o n ( i d ) {
var doDelete
c o n f i r m ( " A r e you s u r e you want t o d e l e t e t h i s w i n d o w ? " ) ;
if(doDelete)
this.issuePortalCommand(
Portal.DELETE_WINDOW_ACTION, " r e f = " + id ); },

, . Ajax
.

11.6.4. Ajax
, Ajax
. , . , JavaScript.
, - .
JavaScript eval (),
. ,
, ,
(JavaScript).
JSON. , -

JSON (. 3), , 5
, .
, , , . ajaxupdate()
r u n S c r i p t ( ) .
ajaxUpdate:
function(request){this.runScript(request.responseText);'
runScript: function(scriptText){eval(scriptText);},

, . ,
, runScript responseText
(" "), runScript () eval () .
: "
runScript () eval() aj axUpdate () ?" ,
.
, . ,
, runScript ()
? . , a j axUpdate () , .
, ,
, .
Ajax
. ,
handleError (), , ajaxUpdate(), , n e t . ContentLoader.
handleError () .
handleError: function(request) {
if (this.options.messageSpanld)

document.getElementById

( t h i s . o p t i o n s . m e s s a g e S p a n l d ) .innerHTML
"Oops! Server e r r o r . Please t r y again l a t e r . " ; } .


messageSpanld ,
"Oops!" .
. .
, . , Ajax. ,
.

11.6.5.
, . -,
, -

Ajax. - - ! -,
Ajax JavaScript. .
.
AjaxWindows.js.
.
.
Ajax .

11.7.

__

, , ,
.
-, , . , ,
, , .
Ajax , , .
, "".
, . ,
Ajax.
, , . Ajax ,
,
. , Ajax, .

, ,
.
, , . , ,
.
XML-
JavaScript.
:
XSLT XML HTML-.


XSLT XML HTML

'""

480

IV. Ajax

Ajax ,
,
. , GIF-
. , ,
, "".
Ajax
"" . XSLT (Extensible Stylesheet Language Transformations ) XML- HTML-. ,
XSLT XML- HTML JavaScript. XML, JavaScript, . ,
, HTML .
, " ",
. , XSLT
Ajax ,
.

12.1.
, "" . ( , Web-, 1 200 , 8 .) ,
.
, ,
. Ajax,
.

12.1.1.
. Web,
.
Google. (www.google.com) .
(
), , .
,
,

12. "" XSLT

481

. 12.1.

, , .. . 12.1
,
,
,
.
, ,
"". - , ,
, . ,
. ,
..
GIF- (,
), , . , , , JavaRanch
(www.JavaRanch.com). GIF-
, . Microsoft Internet Explorer
GIF- , . ,
, , , "",
.
, ,
. - , ,
, , . ,
, , .
, - . ,
, .

. 12.2.

12.1.2.

"" ,
.. (
IFrame) .
Web-,
, .
,
JavaScript.
. ,
. , . ,
.
, . , ,
. ,
, .
. 12.2 , .
,
. ,
- (
, . 12.1).
, .
. , , , , . , "".
,
? ,
. , , ? ,

12. "" XSLT 483

, -
, ,
, .
, ( ). ,
, . onload
onunload, , ,
, . ..
, .
, , ,
.
. , , .. .
; .
,
, , . ,
Ajax. Ajax
,
; ,
, , "".

12.1.3. "" Ajax XSLT


Web- , "";
Ajax.
(
), , . , JavaScript GIF, t n nerHTML DOM.
, ,
, .
Ajax, .
, CSS display
, .
, .
.
, XMLHttpRequest .

. 12.3.
Ajax.
,
, ,

.


Google Maps ,
, . , , . , . ,
, ,
. "" ,
. . 12.3.
Ajax , . ""
, Google Yahoo!, . , "" (, ), , ,
.
"" , , (. 6). Ajax
.

12.1.4.
""' ,
.
XML-, HTML-. XML-. JavaScript- DOM XML,
XML . . XML- ,
HTML- .

12. "" XSLT 485

DOM XML ,
XML-
HTML. , HTML
, , XML-. XML .
HTML- , innerHTML . responseText
XMLHttpRequest, .
,
( ,
). , . ,
. , , ; ,
. , JavaScript- HTML, ,
- , , .
.
, XSLT.
Ajax, XSLT- XML ,
DOM. XSLT,
JavaScript, .
Ajax, ,
, , URL ,
. , URL, . ,
Google, URL , , ,
, . Ajax .
12.5.4.

12.2.
XML- XSLT
, XML- ,
. (,
, 10) JavaScript, XML DOM
HTML-.
XSLT.
XSLT , HTML
XML. XSLT

486

IV Ajax

, XML , HTML. Ajax, XML XLST , HTML- .


XSLT ,
.

12.2.1.
. .
12.1.
12.1.
<form name="Forml" ID="Forml"
onsubmit="GrabNumber();return false;">
// onsubmit
Name: <input name="user" type="text"/>
// 0
<input type="submit" name="btnSearch"
value="Search" />
//
<br/Xbr/>
<div i d = " r e s u l t s " > < / d i v >
// d i v
</form>

"" form . onsubmit <Enter>, , .


GrabNumber(), XMLHttpRequest
. ( , JavaScript.
,
. ,
.)
, , XMLHttpRequest.
. - ,
onblur, GrabNum (); ,
onsubmit.
div , . .
. div -

12 "" XSLT

487

, GIF-. ,
. span. HTML,
innerHTML . div , ,
. , div 100%
, -
.
, onsubmit
false . ,
,
JavaScript- . 12.2.

12.2.2.
: XML
XSL. XML ,
. PHP- , ,
,
XML-. XSL
XML- HTML. XSL ,
, .
, , , XMLHttpRequest
. 12.2.

12.2. '1
function GrabNumber(){
//
v a r urlXML='PhoneXML.php?q=' + d o c u m e n t . F o r m l . u s e r . v a l u e ;
// URL XML
v a r urlXSL=Phone.xsl' ;
// URL XSL
var newlmg=document.createElement('img' );
//
newlmg.setAttribute('src',
'images/loading.gif) ;
//
document.getElementById("results").appendChild(newlmg);
//
LoadXMLXSLTDoc{urlXML,urlXSL,"results");
// 0

, ,
, -

488

IV. Ajax

, , ,
.
LoaciXMLXSLTDoc () URL , XML-, , HTML- . XSLT , XML-. ,
LoadXMLXSLTDoc (),
div, . , ;
" r e s u l t s " .
DOM Web -. .
div . ,
onsubmit ,
. , , ,
.
, , (, Ajax "").
LoadXMLXSLTDoc () , . LoadXMLXSLTDoc (),
12.4, ContentLoader (), . ( LoadXMLXSLTDoc {)),
, if. , . , , ,
XML XSLT.

12.3. :
XML-,
( , Ajax
). XML- ,
. , , XSLT,
, . , ContentLoader ( 12.7). XSLT-
XML- HTML-, .

12 "" XSLT 489

12.3.1. XML-
XSLT, XML, , XSL . XML-, -.
XML-
XML-,
. ,
. ( ) , , . 12.3 XML-,
.
12.3. XML-
<?xml v e r s i o n = " l . 0 " ?>
<phonebook>
<entry>
<company>Company Name</company>
<contact>Contact Name</contact>
<country>Country Name</country>
<phone>Phone Number</phone>
</entry>
</phonebook>
phonebook. entry,
, , . , XML- entry. company. , ,
.
; , ,
.
, ,
. S T O
. ,
12.4, 12.3, XML,
, , .
12.4. XML
<?xml v e r s i o n = " l . 0 " ?>
<phonebook>
<entry>
<company>No Results</company>
// "No R e s u l t s "
<contact>N/A</contact>

490

IV. Ajax
// "N/A"
<country>N/A</country>
<phone>N/A</phone>
</entry>
</phonebook>


, , . company , , . 0 ,
. "N/A" (" "), , &nbsp;, . ,
.
, XML . XML- , . , , XML- .
XML-
, XML- . ,
. , Ajax
,
, . ,
12.5 . . , XML-
12.4
, .
12.5. phoneXML.php: XML-
<?php
// MIME
header("Content-type: text/xml");
echo("<?xml version='1.01 ?>\n");
//
$db = mysql__connect ( "localhost", "ajax", "action");
rnysql_select_db("ajax",$db);
$result = mysql_query("SELECT *
FROM Contacts WHERE ContactName like '%".
//
$_GET['q'] ."%"',$db); ?>
<phonebook>
<?
//
if ($myrow = mysgl_fetch_array($result)) {
do {
//

12. "" XSLT 491


?>
<entry id='<?=$rayrow['id']?>001'>
<company><?=$myrow['companyNarae']?></company>
<contactx?=$myrow['contactName']?></contact>
<countryX?=$myrow['country 1 ]?></country>
<phone><?=$myrow [ ' phone' ] ?x/phone>
</entry>
<?
}while ($myrow - m y s q l _ f e t c h _ a r r a y { $ r e s u l t ) ) ;
}else{
?>
<entry id='001 1 >
// @
<company>No Results</company>
<contact>N/A</contact>
<country>N/A</country>
<phone>N/A</phone>
</entry>
<? } ?>
</phonebook>
XML- ,
MIME text/xml ; , XSLT- ( Mozilla Firefox).
, . ,
,
MySQL . ajax, ,
ajax a c t i o n .
SQL-; WHERE
request, .
, , , DB_DataObject (Pear) (. 3). , , , , .
,
,
, "No Results" 0.

12.3.2. XSLT
XSLT, XML- HTML. XSLT- ,
. -. -

492

IV. Ajax

, XSLT. XSLT- XML- , , . XSLT- .


XSLT
XSLT- . XSLT- . , .

. , XML- . .
XSLT- , . , . , . , XSLT- ,
.
XSLT-
XSLT- . , ;
- . , HTML . XSLT 12.6.
i

12.6. XSLT-
<?xml version="1.0" encoding=>"ISO-8859-l"?>
// XML
<xsl:stylesheet version="l."
xmlns:xsl=
// XSLT
"http://www.w3.org/1999/XSL/Transform">
//
<xsl:template match="/">
// table
<table id="tablel">
//
<tr>
<th align="left">Company</th>
<th align="left">Contact</th>
<th align="left">Country</th>
<th align="left">Phone</th>
</tr>

12 "" XSLT 493


// 0
<xsl:for-each
select="phonebook/entry">
//
<tr>
<tdxxsl:value-of select="company"/></td>
<td><xsl:value-of select="contact"/></td>
<td><xsl:value-of select="country"/></td>
<td><xsl:value-of select="phone"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>

XSLT- XML , XSLT .


, . XML , .
XSLT xsl. / ,
.
, . t a b l e ,
. , , , .
, .
for-each , ,
phonebook/entry.
, . , value-of , XML . XML,
,
s e l e c t . XSLT-
XML, JavaScript- ,
XSLT- XML-
.
, , -.

494

IV. Ajax

12.4. XSL XML


, XSL XML.
XSLT- , - . , , ,
.
, ContentLoader (. 3).
JavaScript- n e t . j s . , ,
.
<script type="text/javascript" s r c = " n e t . j s " X / s c r i p t >
. 12.7 LoadXMLXSLTDoc (), GrabNumber(), 12.2. GrabNumber() URL,
XML-, XSL- , . ,
. 12.7, XML XSL
. .

12.7. LoadXMLXSLTDoc .
//
var xmlDoc;
var xslDoc;
var objOutput;
//
function LoadXMLXSLTDoc(urlXML,urlXSL,elementID){
xmlDoc=null;
xslDoc=null;
// &
objOutput = document.getElementById{
elementld);
// XML XSL
new net.ContentLoader(urlXML,onXMLLoad);
new net.ContentLoader(urlXSL,onXSLLoad);
}
// 0 XML-
function onXMLLoad(){
xmlDoc=this.req.responseXML;
doXSLT();
}
// 0 XSL-
f u n c t i o n onXSLLoad(){
xslDoc=this.req.responseXML;
doXSLT();
}
// ,

12 "" XSLT 495


function doXSLT{){
if (xmlDoc==null || xslDoc==null){ return; }
// XML-
if (window.ActiveXObject){
objOutput.innerHTML=xmlDoc.transformNode(xslDoc);
}
else{
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importstylesheet(xslDoc);
var fragment =xsltProcessor.transformToFragment(
xmlDoc,document);
objOutput.innerHTML = "";
objOutput.appendChild(fragment);
}

_j

,
, .
, xmlDoc xslDoc, XML XSL, . , objOutput,
DOM, . ,
LoadXMLXSLTDoc (), GrabNumber ().
, , . , xmlDoc xslDoc .
, n u l l @.
, ,
.
,
. ContentLoader XML XSL .
ContentLoader URL, . onXMLLoadO
XML- xmlDoc,
doXSLT () .
onXSLLoadO XSL- xslDoc
doXSLT ( ) .
, , ,
, doXSLT () ,
. XML XSL. null,
0. ,
n u l l .
, XSLT- .

IV. Ajax

496

XML XSLT. , 12.7.


, . Internet Explorer t r a n s f ormNode {),
Mozilla XSLTProcessor.
.

12.4.1. Microsoft Internet Explorer


Internet Explorer XML-
XSLT- . t r a n s f ormNode (), XML XSLT
.
if (window.ActiveXObject){
objOutput.innerHTML=xmlDoc.transformNode(xslDoc); }

, t r a n s f ormKode (). , ActiveX. , , XML-, transformNode(),


, XSLT-. innerHTML
, .
, , Internet Explorer. , Mozilla.

12.4.2. Mozilla
Mozilla XSLTProcessor, XML XSL. ,
Opera Safari XMLHttpRequest,
XSLTProcessor, (
12.5.2). 12.8
XML- XSLT .
12.8. XSLT Mozilla
else{
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importstylesheet(xslDoc);
var fragment^xsltProcessor.transformToFragment(xmlDoc,document)I
objOutput.innerHTML = "";
objOutput.appendChild(fragment);

_>

12 "" XSLT 497

. 12.4.
"" Ajax

XSLTProcessor, XML XSL. importStylesheet XSLTProcessor XSL,


XML. XSL, XML-.
XSLTProcessor, t r a n s formToFragmentO. transformToFragment () XML
XSL, .
r e s u l t innerHTML , . , . , , transformToFragment (), r e s u l t . .
, XSLTProcessor, XML
XSL. Mozilla Firefox DOM. Internet Explorer
XML . :
XSL-.
, "" . - Search (""). , . 12.4.
, XSL- . , . 12.4, ,
. ,
, . (Cascading Style
Sheets-CSS).

12.5.

__

XML XSL , , CSS. . ,


, CSS HTML.

IV. Ajax

498

12.5.1.
(Cascading Style Sheets CSS) 2. ,
.
- ,
.
, CSS .
,
. CSS
,
.
12.9.

12.9.
/ /
table{
border: lpx solid black;
border-collapse: collapse;
width: 50%;
}
//
th, td{
border: lpx solid black;
padding: 3px;
width: 25%;

// @
th{
background-color: #A0A0A0;

_J

CSS t a b l e . ,
. border-collapse
collapse. CSS, ,
. ,
. t a b l e
width. , 50%
div. ,
.
table, . , ,
.
, , "" -

12. "" XSLT 499

. 12.5. "" Ajax


CSS

. width 25%
,
CSS
,
.
(background-color) .
font-weight, color ..
, .
, . 12.5.
, ,
CSS .
,
XSLT . CSS
, .

12.5.2.
Ajax . Ajax XSLT . ""
. , , .


. , ,
. , ,
. , , .
Ajax, , (. 9),
, . , , 10, .

500

IV Ajax

Opera Safari
, Opera Safari t r a n s formNodeO, XSLTProcessor.
. Ajax
, XML XSL.
Content Loader,
XML XSLT. , .
Ajax .
XML XSL. , . -
, XMLHttpRequest, .
Ajax, , ,
. ,
Ajax . ,
LoadXMLXSLTDoc {), 12.10. , if,
XSLT. -, else, .
12.10. LoadXMLXSLTDoc G Opera Safari
function LoadXMLXSLTDoc(urlXML,urlXSL,elementID){
var reqXML; var reqXSL;
if {window.XMLHttpRequest && window.XSLTProcessor){
//... do Mozilla client XSLT
} else if (window.ActiveXObject){
//... do Internet Explorer client XSLT
} else{ document.Forml.onsubmit = unction(){return true;(
document.Forml.submit(); }
_ >

12.10 onsubmit
e l s e , . onsubmit,
.

. , XSLT JavaScript,
, Ajax XSLTProcessor.
, Ajax , . Ajax

12. "" XSLT 501

, ..
Opera Safari,
XSLT-
.

12.5.3. XSLT
,

XSLT. , : " XML,
?"
, - ,
, , . , ,
Web- . , Ajax , .
. responseText
XMLHttpRequest HTML-.
, ,
.
HTML- , ,
-. ,
. , , , .
,
.
XSLT, . XML.
. , XSLT- HTML.
, , . XSLT,
, .
, Web- XSLT. -
- (, ), "-''. , . XSLT, HTML.
.

502

IV. Ajax

, JavaScript ,
.
XSL, ,
, ..
XML XSL .
(log file) XML , XML.
, , Ajax .
, ""
Ajax: .

12.5.4.
Ajax : . (
.) ; ,
. Ajax ,
URL , , URL,
, ,
.
, . ,
.
, ,
. ,
,
( ), (
). , .
GrabNumber ().
span, . span spanSave, 12.11 ( getElementByld). , span (
).

12. "" XSLT 503

12.11. GrabNumber, -
function GrabNumber(){
=1
var strLink = "<a href " +
location.href.split("?")[0] + "?q=" +
document-Forml.user.value + '">Save Search</a>";
document.getElementById("spanSave").innerHTML = strLink;
, 12.11,
q , .
"" .
span ,
,
.
12.12 URL
, , .
12.12.
window.onload = f u n c t i o n ( ) {
var strQS = w i n d o w . l o c a t i o n . s e a r c h ;
var intQS = strQS.indexOf("q=");
i f ( i n t Q S != -1){
document.Forml.user.value = s t r Q S . s u b s t r i n g ( i n t Q S + 2 ) ;
GrabNumber();
}
}

onload, . , URL; , .
, GrabNumber (), .
. Ajax
.

12.6.

"" XSLT ,
( !) .
. XSLT . ,

IV. Ajax

504

, ,
DOM. XSLT. , !
XSLT-, ( "" ). , "1' ,
.

12.6.1. XSLTHelper
, XSLT . , , API,
, Internet Explorer Mozilla. , API .
, , ,
XSLT-. , XSLTHelper, , XSLT.
XSLT- : XML- XSL-, . ,
, .
function XSLTHelper( xmlURL, xslURL ) {
this.xmlURL = xmlURL;
this.xslURL = xslURL;
}

, , . URL : XML- XSLT-.


, , API, . , XSLT-,
. ,
-"", , API ,
XSLT-.
, XSLT, . API,
-,
. Java. ,
, :
XSLTHelper.isXSLTSupported{) ;

, , .

12. "" XSLT

505

var helper = new XSLTHelper( 'phoneBook.xml',


1
transformation.xsl' ) ;
var canDoThis = helper.isXSLTSupported();

, :
XSLTHelper.isXSLTSupported = function() {
return (window.XMLHttpRequest && window.XSLTProcessor)
XSLTHelper.isIEXmlSupported();
}
XSLTHelper.isIEXmlSupported = function() {
if ( ! window.ActiveXObject )
return false;
try { new ActiveXObj ect("Microsoft.XMLDOM");
return true; }
catch(err) { return false; }
>

||

. ;
XSLT. - . API XSLTHelper.
. ,
XSLT-
? , ,
API. :
var helper = new XSLTHelper1 ( 'phoneBook.xml1,
'transformation.xsl ) ; 1
helper.loadView{ 'someContainerld );
phoneBook. xml
HTML transformation.xsl, HTML- someCont a i n e r l d . , , loadview()
, , . ,
, . , ,
, :
new XSLTHelper('phoneBook.xml1,
1
1
'transformation.xsl ).loadView('someContainerld );
API , ,
12.13.

506

IV. Ajax

12.13. loadview
loadView: function ( container ) {
/ / XSLT
if ( ! XSLTHelper.isXSLTSupportedO )
return;
//
this.xmlDocument = null;
this.xslStyleSheet = null;
this.container = $(container);
//
new Ajax.Requestt this.xmlURL,
{onComplete: this.setXMLDocument.bind(this)J );
new Ajax.Request( this.xslURL,
{method:"GET", onComplete:
this.setXSLDocument.bind(this)} ) ;

, loadView(), , XSLT . -,
( ),
, . n u l l ,
XML XSL,
. , Ajax XML XSL ,
XML, setXMLDocument ( ) . , XSL, setXSLDocument ().
12.14.
12.14. XML XSL
setXMLDocument: f u n c t i o n ( r e q u e s t ) {
this.xmlDocument = request.responseXML;
this.updateViewIfDocumentsLoaded();
},
setXSLDocument: f u n c t i o n ( r e q u e s t ) {
t h i s . x s l S t y l e S h e e t = request.responseXML;
this.updateViewIfDocumentsLoaded();


XSLTHelper XML XSL. updateViewifDocumentsLoaded(), , , .
updateViewIfDocumentsLoaded() :
updateViewIfDocumentsLoaded: function() {
if ( this.xmlDocument == null |I this.xslStyleSheet == null )
return;
this.updateView();

12. "" XSLT 507


,
. , ,
, this .xmlDocument this .xslStyleSheet,
, null. updateView() 12.15.

updateView: function () {
if { ! XSLTHelper.isXSLTSupportedO )
return;
if { window.XMLHttpRequest && window.XSLTProcessor )
this.updateViewMozilla();
else if ( window.ActiveXObject )
this.updateViewIE();

, . , Mozilla, 12.16.
12.16. Mozilla
updateViewMozilla: function!) {
//
var xsltProcessor =* new XSLTProcessor ();
xsltProcessor.importStylesheet(this.xslStyleSheet);
var fragment - xsltProcessor.
// XSLT-
Trans formToFragment(
this.xmlDocument, document);
// @
this.container.innerHTML = "";
this.container.appendChild(fragment);

__L


(Internet Explorer Mozilla) :
XSLT- . , Mozilla ,
appendChild(), Internet Explorer
, innerHTML. , updateViewlE () :
updateViewIE: function() {
this.container.innerHTML =
this.xmlDocument.transformNode{this.xslStyleSheet);

Internet Explorer
, , ,

508

IV. Ajax

, . ,
.
, xSLTHelper , ,
API, , XSLT. '
, .
""
.

12.6.2. ""
, XSLT, "" ,
, . API,
,
HTML-, , . , - ,
.
. ,
, .
"" , .
, XML XSL, , URL .
, , , .
. , , "" .
function LiveSearch( pageURL, loohupField, xmlURL,
xsltURL, options ) {
this.pageURL = pageURL;
this.lookupField = lookupField;
this.xmlURL = xmlURL;
this.xsltURL = xsltURL;
this.setOptions{options);
//
var oThis - t h i s ;
lookupField.form.onsubmib function(){
oThis.doSearch(); r e t u r n false; };
//
this.initialize();
}

: URL , URL .
options, -

12. "" XSLT

509

. options setQptions(), .
.
setOptions: function(options) {
this.options options;
if ( !this.options.loadinglmage )
this.options.loadinglmage = 'images/loading.gif';
if ( !this.options.bookmarkContainerld )
this.options.bookmarkContainerld = 'bookmark1;
if { !this.options.resultsContainerld )
this.options.resultsContainerld - 'results';
if { !this.options.bookmarkText )
this.options-bookmarkText = 'Bookmark Search';
>'

setOptions {) ,
TextSuggest (. 10), extend()
Prototype .
, ,
, , , , , , .
, options
,* . options
, . .
,
:
var oThis = t h i s ;
lookupField.form.onsubmit = function(){
oThis.doSearch{); return false; };
,
HTML-, onsubmit.
<form name="Forml" onsubmit="GrabNumber();return false;">

( , , HTML- ),
, HTML-.
GrabNumberO doSearch(), doSearch() ,
. , , doSearcht):
doSearch: function{) {
if ( XSLTHelper.isXSLTSupported() )
this.doAjaxSearch();
else this.submitTheFormt);
},

510

IV. Ajax

"" , XSLT, XSLT-,


API xsLTHelper , XSLT- . , .
doSearch(), XSLT. . .
, .
submitTheForm: function() {
var sesrchForm = this.lookupField.form;
searchForm.onsubrait function() { return t r u e ; };
searchForm.submit();
t

onsubmit ,
t r u e .
. submit () "" HTML, . ;
, .
Ajax.
doAj axSearch: function() {
//
this.showLoadinglmage();
var s e a r c h U r l = t h i s . a p p e n d T o U r l ( this.xmlURL,

'q1,

// URL
this.lookupField.value);
// XSLT-
new X S L T H e l p e r t s e a r c h U r l , t h i s . x s l t U R L ) . l o a d V i e w (
this.options.resultsContainerld);
//
this.updateBookmark

();

doAj axSearch () ,
,
, .
, .
: . ,
. .
.
, " ".
.

12. "" XSLT

511

showLoadinglmage: function() {
var newlmg = document.createElement('img1);
newlmg.setAttrlbute('src', this.options.loadingImage );
document.getElementById(
this.options.resultsContainerld).appendChild(newlmg);
},

0 URL . URL
xmlURL, q=, ,
. () , URL
( ).
appendToUrl: function(url, name, value) {
var separator = ' ? ' ;
if (url.indexOf(separator) > 0; ) separator = '&';
return u r l + separator + name + '=' + value;
},
XSLT- .

XSLT- , .
new XSLTHelper(searchUrl,
this.xsltURL).loadView(this.options.resultsContainerld);
. ,
.
updateBookmark().
updateBookmark: function() {
var c o n t a i n e r document.getElementByldt
this.options.bookmarkContainerld);
v a r bookmarkURL = t h i s . a p p e n d T o U r l (
1
this.pageURL, 'q , t h i s . l o o k u p F i e l d . v a l u e );
if ( c o n t a i n e r )
c o n t a i n e r . i n n e r H T M L = '<a href^"1 +
bookmarkURL + '" > ' + t h i s . o p t i o n s . b o o k m a r k T e x t + ' < / a > ' ;
}

container . URL ,
pageURL.
q= . innerHTML URL.
,
q=someValue. , ? ,
t h i s . i n i t i a l i z e ( ) ; .

512

IV. Ajax

, ,
. , , , i n i t i a l i z e ()
. :
i n i t i a l i z e : function{) {
var currentQuery = document.location.search;
var qlndex = currentQuery.indexOf('q=');
if ( qlndex != -1 ) {
this.lookupField.value =
currentQuery.substring( qlndex + 2 );
this.doSearch();
}

i n i t i a l i z e ()
q. ,
. doSearch ( ) . .

12.6.3.
, .
XSLTHelper,
XSLT .

'" . , "" , Web .
-
:, .
.

12.7.
3 Ajax. , ! .
, , , . ,
, ,
.
XSLT-,
i.ML HTML-, in div. JavaScript
, XML , . XML XSLT.

12.

" UCnoilbJUaatiucivi A j u i

viw

, XSLT "" , , . . , - . - ? , innerHTML ,


, . , Ajax , ,
.
XSLT RSS
, DOM XML XSLT.
, ,
Ajax. Ajax, Web-: RSS.

. . .
RSS-
Ajax
Web-
Ajax

IV Ajax

Ajax .
,
. , ,
Ajax ,
Web-. , Web , .
Web- XML RSS
(Really Simple Syndication ), RDF (Resource Descriptor Framework ) Atom
. , , , , ,
, .. Ajax ,
, XML- .

XML-, Web-.
, .

13.1.
XML ,
Web-.
XML . , XML-
Web-, .
, , . ,
. , ,
, .
XML . , , Web-, XML-. ,
, , , JavaCrawl.com. , RSS- , XML- Web-,
, .
, Ajax. Ajax
Web-, , Ajax .
RSS- JavaScript,

, 13.1. , RSS-

, . , RSS .
,
. , Ajax,
XML- , .

13.1.1. XML-
XML- .
.
: , , ,
.
, . 13.1.
, .. .
, JavaRanch, XML-.
"" XML- Web- (, JavaLobby),
.
. 13.1 RSS, RDF
Atom. , XML- .
XML. , , XML-, -

518

IV. Ajax

13.1.

d e s c r i p t i o n ,

link

URL Web- HTML, h t t p : / / r a d i o . j a v a r a n c h . c o m /



pascarello

title

,
.
Web-

JavaRanch.com

. , ,
, .
,
.
RSS
(Really Simple Syndication ), RSS-.

13.1.2. RSS
XML- Ajax
RSS, RSS-.
DOM XML ,
. , RSS :
. , ;
.

RSS. ,
RSS, , , .. . 13.1, RSS
.
RSS-. , RSS-,
. ,
.
RSS . 13.2 .
, , .
, , .
, , , .

13. Ajax,

519

13.2.

category

cloud


c l o u d ,
. ,

-

copyright

docs

URL,
RSS

h t t p : //backend.
userland.com/rss

generator

, ,

Pebble

image

h t t p : //pebble.
soundforge .net/
common/images/
powered-bypebble.gif

language

En

lastBuildDate

managing e d i t o r ,

pubDate

rating

PICS . .
http://www.w3.org/PICS/
(
RSS-),

skipDays

skipHours

textlnput

ttl

(Time to Live TTL),


,
,

webmaster

pascarello@
javaranch.com

webmaster@
javaranch.com

520

IV. Ajax


RSS-, . , .

, RSS
.
: .
RSS , .
, , . ,
, ; , , .
RSS , , .. , ,
. 13.3.
RSS .
( t i t i l e ) , , (description) :
. , ,
d e s c r i p t i o n . ,
, ,
RSS-. , : " . . 10".
link, URL
.
RSS-
, (, ) RSS-.
, RSS-. RSS
http://backend.userland.com/rss.
RSS, RSS- Ajax.

13.2.
RSS-,
XML Web- ,
NET JSP, . Ajax
Web-, .
, Ajax Web, , .NET JSP. -

13. Ajax,

521

13.3.

author

P a s c a r e l l o @ j a v a r a n c h . com

category

comments

URL , h t t p : / / r a d i o . j a v a r a n c h . c o m /
p a s c a r e l l o / 2 0 0 5 / 0 5 / 2 5 / 1 1 1 7 0 4 3
999998.htmltcoiranents

description

Ajax
,
Web-

enclosure

-,

<enclosure u r l = " h t t p : / / r a d i o .
javaranch.com/pascarello/media/
TheAj axInActionSong.mp3
"length="5908124"type="audio/
mpeg"/>

guid

, h t t p : / / r a d i o . j a v a r a n c h . c o m /

pascarello/2005/05/25/1117043
999998.html

link

URL

http://radio.javaranch.com/
pascarello/

pubDate

, 25 2005 ., 17:59:59 GMT

source

RSS,

<source u r l = " h t t p : / / r a d i o .
javaranch.com/pascarello/
1
blog-xmls-Eric s Blog</source>
Ajax

title

, RSS- . ( Mozilla, . 13.6.1.


, , Mozilla,
7.)

13.2.1.
Web-,
. , .

. 13.2. RSS-

, ; XML- RSS,
Web-. Web, Web-.
, . RSS-,
-, .
, , .
. 13.2.

. , : , .
, , . 13.2.

( ). CSS. .
"", "" "".
,
.
.

13.2.2. HTML-
. , ,
, div span. ,
, . 13.3.

. 13.3. RSS-

,
CSS (. 2).
, , ,
CSS. 13.1 , XML-.
13.1. HTML-,
<form name="Forml">
< ! div >
<div id="divNewsHolder">
< ! div >
<div id="divNewsTitle">
< ! >
<span id="spanCount">Loading</span>
< ! >
&nbsp;Ajax News Viewer
</div>
< ! >
<div id="divAd">
< ! 0 >
<div id="divNewsl">
Loading Content...
</div>
< ! >
<div id="divNews2">
Loading Content...
</div>
</div>
<i
0 >
<div id="divControls">
<!
>
<input type="button" name="btnPrev"

524

IV. /

. 13.4. HTML
CSS

i d = " b t n P r e v " value="<BACK" />


<input type="button" name="btnPause"
i d = " b t n P a u s e " value="PAUSE" / >
i

< i n p u t t y p e = " b u t t o n " name= "btnNext"


i d = " b t n N e x t " value="NEXT>" / >
<hr/>
<!
>
< s e l e c t name="ddlRSS">
</select>
< i n p u t t y p e = " b u t t o n " name="btnAdd"
value="Add Feed" />
</div>
</div>
</form>

div divNewsHolder , ,
. div divNewsTit l e . div
span , - . .
, .
divAd . ,
RSS-, . divAd div, divNewsl divNews2 ,
RSS-. CSS JavaScript,
.
div divCont r o l s . .
div "", "" "" .
XML-, . ,
, . 13.4.
. 13.4 , HTML, CSS .
. 13.3, , div (divNewsl divNews2) ,
.

13 Ajax,

525

13.2.3. CSS-
CSS Web- , . 13.4:
. ,
CSS. , HTML-.
, , div .

divNewsHolder
. RSS-
.
div, 100%
. ,
, . CSS 13.2.
13.2. CSS
/ / div
#divNewsHolder{
width: ;
border: 2px solid black;
padding: ;
)
// div
#divNewsTitle{
font-size: 20px;
height: 26px;
background-color: #BACCD9;
//
line-height: 26px;

//
#spanCount{
// ""
float: right;
font-size: 15;
padding-right: 10px;
>


# . , div, divNewsHolder. divNewsHolder
, 0.

, .
divNewsTitle , . l i n e - h e i g h t

. 13.5. d i v

CSS

div. , , 20 div.
,
div.

spanCount {
). float , r i g h t . , - (
).
, , . padding-right ,
. ;
. 13.5.
. 13.5 ,
, . Loading
div, div
. div, ,
.
div.

, ,
( 13.3). RSS-. div divNewsl divNews2
; .
, , .
13.3. CSS d i v
// divAd
#divAd{
// width: 100%;
//
height: 400;
//
overflow: hidden;
//
border-top: 2px solid black;

13 Ajax,

527

border-bottom: 2px solid black;


}
// div
#divNews1, #divNews2{
//
width: 100%;
height: 40Opx;
background: #D9CCBA;
//
position: relative;
// ,
overflow: auto;
// div
left: Opx;

1
/ / d i v
# d i v N e w s l { t o p : Opx;}
// d i v
# d i v N e w s 2 { t o p : -4Q0px;}

divAd , span RSS-. 100%, 400. , ,


overflow hidden. ,
- 400 , .
div
, .
2 . , . ,
4 , 2 , ..
.
div, , divNewsl divNews2 . , .
, div . ( r e l a t i v e ) div
divAd,
(absolute) , .
overflow div auto,
.
0 ,
div, .
, div, , . ,

. 13.6. CSS d i v

. divNewsl
0 . ,
div. divNews2 -400.
? , , . 13.4 13.5,
div ,
div. 400 , divNews2 400 , div ( , divNewsl).
. 13.6, , , . 13.5, div
.
div , . 100%,
. , , , ,
.

, CSS, . , .
, ( 13.4).
13.4. CSS d i v
// d i v
//
#divControls{
b a c k g r o u n d - c o l o r : #BACCD9;

13. Ajax,

529

//
text-align: center;
/ /
padding-top: 4;
padding-bottom: 4px;
}
//
#divControls input{
//
width: lOOpx;
background-color: #8C8C8C;
color: #000000;
f o n t - s i z e : ;
}

div divControls
CSS , .
, . . , . div ,
,
.
CSS- , . ,
divControl, , :
div, . ,
, div.
.
, width
, , ..
. , . ,
. . 13.7

.
. 13.7 , div.
, , , , .
CSS , Web- .
RSS-!

530

IV Ajaxe

. 13.7. CSS

13.3. RSS-
.
ContentLoader (
). RSS-
.

13.3.1.
,
for
. . ,
, ""
.

;
.
JavaScript
, . ,
, . , 13.5,
.

13 Ajax, & 53"!

13.5.
var flipLength = 5000; var timeColor = 100;
var strErrors = "<hr/>Error List: <br/>"
var arrayRSSFeeds = new Array(
"http://radio.javaranch.com/news/rss.xml",
"http://radio.3avaranch.com/pascarell0/rss.xml",
"http://radio.]avaranch.com/bear/rss.xml",
"http://radio.3avaranch.c0m/lasse/rss.xml");

13.5 , . , f l i pLength, , , . ,
, 5000 . - timeColor
"" . ,
.
s t r E r r o r s . ,
; , . , , arrayRSSFeeds.
URL RSS, .
RSS
JavaRanch.com.
,
13.6,
RSS- .
13.6. ,
var
var
var
var
var
var
var

currentMessage = 0;
layerFront = 2;
timerSwitch;
bPaused = false;
arrayMessage = new Arrayt);
intLoadFile = 0;
bLoadedOnce = false;

,
13.6, currentMessage. , . - ,
. layerFront . RSS-, . layerFront.

532

IV. Ajax

timerSwitch , , . , bPaused.
:
true , f a l s e .
arrayMessage , RSS.
, . , ,
,
arrayMessage.
, intLoadFile, . ,
, arrayRSSFeeds .
, , . RSS- URL.
. XML- .
, , -,
( , ). ,
. ,
RSS-.

13.3.2. Ajax
, Ajax-,
, Web- . Ajax ContentLoader.

ContentLoader . 13.7 , ( ; . 13.5), URL
, ContentLoader.
13.7. JavaScript
window.onload = function(){ var loader= new Array()
for(i=O;i<arrayRSSFeeds.length;i++){
loader[loader.length] = new net.ContentLoader(arrayRSSFeeds[i],
BuildXMLResults,BuildError);}}

13. Ajax, 533

, 13.7, onload. loader, .


arrayRSSFeeds URL RSS, .
loader, ContentLoader.
URL , BuildXMLResults(), , BuildError (),
. , XML-.

BuildXMLResults()
( ), BuildError () ( -
). BuildXMLResults XML- . BuildError () . ,
. 13.8.
13.8. XML- JavaScript
f -unction BuildXMLResults () {
var xmlDoc = this.req.responseXML.documentElement;
var RSSTitle =
xmlDoc.getElementsByTagName('title')[0].firstChild.nodeValue;
var xRows = xmlDoc.getElementsByTagName('item') ;
for (iOO; iCXxRows . length; iC++) {
intMessage = arrayMessage.length;
arrayMessage[intMessage] = new Array(
RSSTitle,
xRowsfiC] .getElementsByTagName{'title') {0]
.firstChild.nodeValue,
xRows[iC].getElementsByTagName('link' ) [0]
.firstChild,nodeValue,
xRowsfiC].getElementsByTagName('description')[0]
.firstChild.nodeValue);
}
UpdateStatusO;

BuildXMLResults (), 13.8, XML, responseXML .


XML xmlDoc,
RSS-. .
, xRows.
, , arrayMessage.
RSS-, ,

534

IV Ajax

. , xRows. ,
UpdateStatus () ( 13 9)
.
13,9. ,
function UpdateStatus(){
intLoadFile++;
if{intLoadFile < arrayRSSFeeds.length){
document.getlementById("divNews2").innerHTML "Loaded File " + intLoadFile + " of "
+ arrayRSSFeeds-length + strErrors;
Jelse if(intLoadFile >= arrayRSSFeeds.length && 'bLoadedOnce){
document.getEleraentByldf"divNews2").innerHTML =
"Loading Completed" + strErrors;
if{arrayMessage.length == 0){
alert("No RSS information was collected."); return false;
}
bLoadedOnce true;
var timerX = setTimeout("ChangeView()",1500);
}
}

13.9, UpdateStatus () . -, ; -, , -.
, intLoadFile, . intLoadFile
, innerHTML divNews2 .
( ), .
- ,
.
arrayMessage. ,
, false.
, bLoadedOnce t r u e
Changeview(). ,
. , XML-,
BuildError() ( 13.10).
13.10. , XMLHttpRequest
function BuildError(){
strErrors += "Error:" + "" + "<br/>"; UpdateStatus();
}

13 Ajax,

535

. 13.8.
,

BuildError() .
, , . s t r E r r o r s ,
UpdateStatus {), . , , Web-
(. 13.8).
, . . 13.8 ,
( )
. , , . JavaScript, ChangeView{).
,
, .

73.4.
, , .
, , -, DHTML.
div inner HTML, , .
CSS- z-lndex ,
div. ,
- .

536

IV. Ajax

13.4.1. ,

. , , . 0%,
. 100%- .
, , Internet Explorer Mozilla. ! -, .
Mozilla (opacity), Internet Explorer ,
( 13.11).
13.11. CSS
.{opacity:
.opacl{opacity:
.opac2{opacity:
.{opacity:
.opac4{opacity:

.0;filter:
.2;filter:
.4;filter:
.6;filter:
.8;filter:

alpha(opacity=0);}
alpha{opacity=20);}
alpha(opacity=40);}
alpha(opacity=60);}
alpha(opacity=80);}

13.11 , ,
.
CSS, JavaScript, - . CSS, ; ,
. CSS JavaScript-, , .
, RSS- div.

13.4.2.
13.3.2, ,
ChangeView(). div .
, CSS
div z-lndex. 13.12.
13.12. ChangeView()
// ChangeView()
f u n c t i o n ChangeView(){
// RSS-
s t r D i s p l a y - "<span class=hRSSFeed'>" +
arrayMessage[currentMessage][0] + "</span>: "
//

13 Ajax,

537

strDxsplay += "<span class='itemTitle'V +


arrayMessage[currentMessage][1] + "</spanxhr>";
//
strDisplay += arrayMessage[currentMessage][3]
+ "<hr>";
// URL
=1
strDisplay += "<a href " +
arrayMessage[currentMessage][2] +
111
title='View Page'>View Page</a>";
// 0
document.getElementById("spanCount").innerHTML =
"Message " + (currentMessage+1) +
" of " + arrayMessage.length;
var objDivl document.getElementById("divNewsl");
var objDiv2 = document.getElementByldf"divNews2");
//
if(layerFront == 1){
objDiv2.className = "opacO";
objDivl.style.zlndex = 1;
objDiv2.style.zlndex = 2;
objDiv2.innerHTML = strDisplay;
layerFront = 2;
}
else{
objDivl.className = "opacO";
objDiv2.style.zlndex = 1;
objDivl.style.zlndex = 2;
objDivl.innerHTML = strDisplay;
layerFront = 1;
}
//
SetClass(O);

_J

ChangeView() . -,
HTML- , RSS; -, div .
HTML- , . ,
.
, , RSS , arrayMessage. span
CSS RSSFeed.
, .
span CSS itemTitle,
. , .
arrayMessage. ,

538

IV. Ajax

; HREF
URL. '"View Page" ('' "),
. , ,
Web- RSS-.
,
RSS-. innerHTML 0 spanCount, arrayMessage
. div . div zlndex , , CSS, .
div, . , CSS; ,
SetClassO .

13.4.3, JavaScript
div , .
CSS. , ( ).
,
.
13.4.1, /
CSS.
. , 13.13,
.
13.13. CSS
// S e t C l a s s O
function
SetClass(xClass){
//
if(xClass<5){
// c l a s s N a m e
document.getEleraentById("divNews" +
//
layerFront).className = "opac" + xClass;
timerAmt = s e t T i m e o u t ( " S e t C l a s s { " +
(xClass+1) + " ) " , t i m e C o l o r ) ;
}
else{
// CSS
document.getElementByld("divNews"
+ layerFront).className = "";
//

13 Ajax,

539

currentMessage++;
/ /
if(currentMessage>=arrayMessage.length)
currentMessage 0;
//
if(IbPaused)
timerSwitch = setTimeout(
"ChangeView()",flipLength);
}
_ J

13.13 S e t c i a s s ( ) ,
xClass.
, .
,
.
CSS, ,
. , ,
CSS, CSS,
className .
, . setTimeout .
JavaScript, , /.
SetClass (), , 1.
flipLength, 13.3.1.
e l s e ,
CSS, div.
div CSS . 100% ( );
, div
, .
1 currentMessage , . , ,
arrayMessage. , . ,
. ChangeView()
setTimeout,
flipLength. , ,
bPaused true. 13.5.2.
, . ,

. 13.9. 5 6

,
, .
. 13.9, ,
. (6) , , 31 . ,
, , ,
.

13.5.
, ,
( ). , , RSS-.
. ,
-
RSS- . , .
,
, .

13.5.1.
, .
. 13.9. URL ,
;

13 Ajax,

541

Add Feed (" "). 13.3; ,


( 13.14), ContentLoader, , s e l e c t .
13.14. JavaScript, RSS
function LoadNews(){
var sel = document.Forml.ddlRSS;
if(sel,options[sel.selectedlndex].className!="added"){
var url = sel.options[sel.selectedlndex].value;
sel.options[sel.selectedlndex].className="added";
var loaderl = new net.ContentLoader(url,
BuildXMLResults);
}
_ !

LoadNews (), btnAdd. URL RSS s e l e c t ,


ddlRSS.
RSS- s e l e c t , , . CSS. ,
, ,
RSS . ,
className added.
ContentLoader URL BuildXMLResults (). - ,
ContentLoader. , , , , RSS-
, 13.15.
<select name="ddlRSS">
<option
value="http://radio.javaranch.com/frank/rss.xml">
Frank</option>
<option
value="http://radio.javaranch.com/gthought/rss.xml">
Gregg</option>
</select>
<mput type="button" name="btnAdd"
value="Add Feed" onclick="LoadNews()" />

542

IV Ajax

. 13.10. RSS-

URL RSS,
RSS-. RSS- JavaRanch.
btnAdd onclick,
LoadNews (). CSS, .
, .
.added{background-color: silver;}
CSS CSS, .
, . ,
.
. 13.10, RSS- Frank (
). , Gregg, ,
. ,
31 54. .
"", "" "".

13.5.2.
. , ,
, ,

13. Ajax, S43

. , . , currentMessage ,
. 13 16 , .
13.16. JavaScript,
/ / MoveFeed()
function MoveFeed {xOption){
// @ ,
if(xOption == 0){
//
if(IbPaused){
bPaused true;
if(timerSwitch)
clearTimeout(timerSwitch) ;
document.getElementById{"btnPause").value = "RESUME";
}
// //
else(
bPaused = false;
setTimeout("ChangeView()",300);
document.getElementById("btnPause").value "PAUSE";
}
}
// 0
else{
if(timerSwitch)
clearTimeout(timerSwitch);
if(xOption " -1)currentMessage += - 2 ;
if(currentMessage < 0)
currentMessage = arrayMessage.length
+ currentMessage;
ChangeView();
}
_ >

MoveFeed () , : , .
.
, MoveFeed () 0,
1, 1.
( ) ( - ).
, bPaused t r u e ,

544

IV Ajax

timerSwitch. , ,
clearTimeout. "RESUME".
, , . bPaused
false; ChangeView() "PAUSE".
.

. , , . ,
1 . ,
currentMessage 2. - , currentMessage
,
1 1 , . , currentMessage
,
.
,
. , . currentMessage,
ChangeView{) . ,
, ( 13.17),
MoveFeed ( ) .
13.17. o n c l i c k
v a l u e = " < " o n c l i c k = " M o v e F e e d { - 1 ) " >
v a l u e = " PAUSE " o n c l i c k = " M o v e F e e d ( 0 ) " >
value="NEXT>" o n c l i c k = " M o v e F e e d ( 1 ) " >

onclick. MoveFeed(),
: -1 ; 0 , 1
. , .
, ,
RSS-. . 13.11 ,
: btnAdd
RESUME (""). ,
, ,
RSS- , Web-,
.

. 13.11.
RSS- ,
RESUME

13.6.
Ajax RSS-
HTML-, , .
RSS-
Web-.
Web- HTML-, RSS .
Web-, . ,
,
, .
; ,
Mozilla .

13.6.1. Mozilla
Microsoft Internet Explorer, Firefox Mozilla - . Ajax
Web-, , .
,
, . Mozilla
JavaScript, Tools =?
Web Development =- JavaScript Console ( => Web-
= JavaScript) (. 13.12).

546

IV Ajax

. 13.12. Mozilla
T o o l s => Web
D e v e l o p m e n t =>
JavaScript
Console
( =^
W e b - =$>
J a v a S c r i p t )

. 13.13.
" ",

XMLHttpRequest

JavaScript Console ( JavaScript), (. 13-13).


. 13.13 "permission denied" (" "), XMLHttpRequest. . ,
Mozilla , XMLHttpRequest
, .
about: conf ig , .
,
, . , , , .
, ? JavaScript.
, , , PrivilegeManager, 7. ,
. 13.18 ,
, .
:;:. 13.18. Security Privilege Manager
if(window.netscape &&
window.netscape.security.PrivilegeManager.enablePrivilege)
n e t s c a p e . s e c u r i t y . P r i v i l e1g e M a n a g e r . e n a b l e P r i v i l e g e (
'UniversalBrowserRead );

, P r i v i l e g e Manager. , UniversalBrowserRead.
ContentLoader, Ajax.

loadXMLDoc, 13.19.

13 Ajax,

547

. 13.14. ,

13.19. " loadXMLDoc


net.ContentLoader.prototype.loadXMLDoc = function(
url,method,params,contentType){
if(window.netscape &&
window.netscape.security.PrivilegeManager.enablePrivilege)
netscape.security.PrivilegeManager.enablePrivilege(
'UniversalBrowserRead1);

, onReadyState ( 13.20).
13.20, onReadyState
net.ContentLoader.onReadyState=function(){
if(window.netscape &&
window.netscape.security
.PrivilegeManager.enablePrivilege)
netscape.security.PrivilegeManager
.enablePrivilege('
UniversalBrowserRead');

.
. -,
(. 13.14).
Allow (), . ,

548

IV. /'

Remember t h i s decision (" "). ,


XMLHttpRequest .
, , Mozilla, Firefox Netscape. , 1^
, . ,
, Web , , .

13.6.2.
XML-, . , ,
.
, XML. XML- , HTML .
, .
, ,
.
XML- , . , , XML-. ,
.
,
XML-.

13.7.
, RSS- ,
, . , .
"-" (Model-View-Controller MVC). 3
4, MVC
.
, , .

13 Ajax, 549

13.7.1.
RSS- .
,
. Ajax DHTML- , Web-,
.
, ,
, RSS-.
, , 10, Prototype.
RSS-.
RSS- XML-, URL, . , , , ,
. , item,
. ,
, , 13.21.

13.21. RSSFeed . ^^^^^^^^


RSSFeed = Class.create();
RSSFeed.prototype = {
initialize: function( title, link, description ) {
this.title - title;
this.link = link;
this.description = description;
this.items = [];

addltem: function(anltem) {
this.iterns.push(anltem); }

RSSFeed
C l a s s . c r e a t e ( ) Prototype. , , , i t n i t i a l i z e . , RSS-
:
var rssFeed = new RSSFeed{ 'JavaRanch News',
'http://radio.javaranch.com/news/',
'Stories from around the ranch' );
, , RSSFeed.
, RSSFeed API addltem,
.
, . , RSS,
, 13.22.

550

IV Ajax
13.22. RSSltem
RSSItem = Class.create();
RSSltem.prototype = {
initialize: function( rssFeed, title, link, description ) {
this.rssFeed = rssFeed,this.title = title;
this.link = link;
this.description = description;

J
};

. t i t l e ,
l i n k description, , RSSFeed, . , ,
:
var rssFeed = new RSSFeed( 'JavaRanch News',
'http://radio.javaranch.com/news/',
'Stories from around the ranch' );
var feedl = new RSSItem( rssFeed,
'Win a copy of JBoss',
'http://radio.javaranch.eom/news/05/07/20/9.html',
'Text of A r t i c l e ' );
rssFeed.addltern(feedl);

. RSS- . - RSSFeed RSSltem.


. ,
XML- Ajax.
,
Ajax XML- RSSFeed.
, .
var rssFeed = RSSFeed.parseXML{ rssXML );

, XML-, Ajax, RSSFeed; RSSFeed. parseXML(),


13.23.
RSSFeed.parseXML = function(xmlDoc) {
var rssFeed = new RSSFeed(
RSSFeed.getFirstValue(xmlDoc, 'title'),
RSSFeed.getFirstValue(xmlDoc, 'link' ),
RSSFeed.getFirstValue(xmlDoc, 'description'));
var feedltems = xmlDoc.getElementsByTagName('item');
for ( var i = 0 ; i < feedltems.length ; i++ ) {
rssFeed.addltern(new RSSltem(rssFeed,
RSSFeed.getFirstValue(feedltems[i], 'title'),
RSSFeed.getFirstValue(feedltems[i], 'link' ),
RSSFeed.getFirstValue(feedltems[i], 'description'))

13 Ajax,

551

}
r e t u r n rssFeed;
}

XML-, . t i t l e , l i n k d e s c r i p t i o n , RSSFeed.
item, RSSltem. addltemO,
RSS-.

. getFirstValue 13.24.
13.24.
RSSFeed.getFirstValue = function(element, tagName) {
var c h i l d r e n = element.getElementsByTagName(tagName);
if { c h i l d r e n == n u l l I | c h i l d r e n , length *== 0 )
r e t u r n "";
if ( c h i l d r e n [ O ] - f i r s t C h i l d &&
children[O].firstChild.nodeValue )
return children[O].firstChild.nodeValue;
r e t u r n "";
}

, . , , RSS, , .
,
RSS- ( ). . , , . , g e t T i t l e ( ) / s e t T i t l e ( ) ,
. JavaScript, , (, p r i v a t e / p r o t e c t e d Java), . , , .

13.7.2.
, . RSSFeed, RSSltem, RSSReader
, RSSltemView, RSSltem RSSFeed -

552

IV. Ajax

HTML-,
HTML-. , , 13.25 13.25. RSSItemView
RSSItemView = C l a s s . c r e a t e ( ) ;
RSSItemView.prototype = {
i n i t i a l i z e : f u n c t i o n ( r s s l t e m , feedlndex,
t h i s . r s s l t e m = rssltem;
t h i s . f e e d l n d e x f e e d l n d e x + 1;
t h i s . i t e m l n d e x = i t e m l n d e x + 1;
t h i s . n u m F e e d s = numFeeds;

itemlndex,

numFeeds)

. RSSltem. ,
.
, - , .
. feedlndex . itemlndex ,
RSSFeed. numFeeds
, .
. , ,
, " 1 7 3 5". , ,
, ( ) .
, HTML-.
. , ( 13.26).
13.26. HTML-
toHTML: function () {
var out = ""
out += '<span class="rssFeedTitlePrompt">RSS Feed '
out += '(' + this.feedlndex + of ' + this.numFeeds + ') : ';
out += '</span>';
out += '<span class="rssFeedTitle">';
out += '<a href="' + this.rssltem.rssFeed.link + '">' +
this.rssltem.rssFeed.title + '</a>';
out += '</span>';
out += '<br/>';
out += '<span class="rssFeedItemTitlePrompt">Article ';
out += '(' + this.itemlndex + ' of * +
this.rssltem.rssFeed.items.length + ') : ' ;
out += '</span>';

13. Ajax,

553

. 13.15. RSS- ( ): RSS-

out +=
o u t +=
this.rs
o u t +=
out +=
out +out +=
return

'<span c l a s s = " r s s F e e d I t e m T i t l e " > ' ;


1
'<a href-" + t h i s . r s s l t e m . l i n k + ' " > ' +
sltem.title + '</a>';
'</span>';
'<div class="rssItemContent">';
this.rssltem.description;
'</div>';
out;

toHTML , . RSS- (
) : RSS-. l i n k rssFeed HREF , t i t l e . span
CSS ( , ), . . 13.15.
( ) : RSS-. HREF
l i n k RSS-, t i t l e
. , . 13.16,
CSS .
toHTML div,
RSSltem ( d e s c r i p t i o n ) .
:
out += '<div class="rssItemContent">';
out += t h i s . r s s l t e m . d e s c r i p t i o n ;
out += '</div>';
CSS rssltemContent. ,
. ,
auto overflow,
.
CSS .

554

IV. Ajax

. 13.16. ( ) RSS-

. 13.17. ( ) RSS-

.rssItemContent {
border-top : lpx solid black;
width : 590px;
height : 350px;
overflow : auto;
padding : 5px;
margin-top : 2px;
}

, . 13.17. , . 13.18 ,
RSSitemView. ,
, .
toString: function() {
return this.toHTMLO;
J

RSSItemView Result

. 13.18. R S S I t e m V i e w

, t o s t r i n g , , HTML. ,
innerHTML , , ( HTML-). , , HTML- innerHTML div
contentDiv.
var rssItemView1 - new RSSItemView( anRSSFeed, 0, 0, 5 );
$('contentDiv ). innerHTML = rssItemView;
(, $() Prototype, DOM .) ,
,
, .

13.7.3.
RSSReader ,
, ,
RSS-. , - ,
,

556

IV. Ajax

. ,
, / -. ,
. , .
1. .
2. -.
3. .
4. RSS- Ajax.
5. .
, , Prototype ( ), Rico (
, )
net.ContentLoader ( Ajax). , .


.
, ,
- , ,
. , RSSReader , 13.27.
13.27.* RSSReader ;
RSSReader = Class.create*);
RSSReader.prototype = {
initialize: function( readerld, options ) {

^^

//
this.id = readerld;
this.transitionTimer = null;
this.paused = false;
t h i s . v i s i b l e L a y e r = 0;
//
this.setOptions(options);
//
this.start{);
),

: .
, -

13. Ajax, 557

DOM.
, applyButtonBehaviors. ,
, .
( ) ,
.
setoptions. , s t a r t
, . , .
setoptions, 13.28. setoptions .
13.28. setoptions

jjjl

setOptions: function(options) {
this.options = {
s l i d e T r a n s i t i o n D e l a y : 7000,
fadeDuration : 300,
errorHTML : '<hr/>Error r e t r i e v i n g c o n t e n t . < b r / > '
}.extend(options);

setOptions , . slideTransitionDelay
, ""
. fadeDuration ,
"" ( , "" ""). , RSS- errorHTML, HTML, .
, , . ,
,
rssFeeds .
, setoptions . ,
, .
var options = {
rssFeeds: [ "http://radio.javaranch.com/news/rss.xml",
" h t t p : / / r a d i o . j avaranch.com/pascarello/rss.xml",
"http://radio.javaranch.com/bear/rss.xml",
"http://radio.javaranch.com/lasse/rss.xml" ] };
var rssReader = new RSSReader{'rssReader', options );
, . s t a r t ,
.
, . , ,
, 13.29.

IV. Ajax

558

13.29. start :|
start: function() {
this.applyButtonBehaviors();
new Effect.FadeTo( this.getLayer(1), 0.0, 1, 1, {} );
this.loadRSSFeed(0,true);
this.startSlideShow{false);

},

applyButtonBehaviors onclick
/ , /, .
. , ,
div, . ,
, Rico, ,
, . loadRSSFeed Ajax , startSlideShow
slideTransitionDelay, -. loadRSSFeed
"' RSS- Ajax", startSlideShow
' -". , , , 13.29
applyButtonBehaviors.
, applyButtonBehaviors
, .
13.30.
13.30. applyButtonBehaviors .
applyButtonBehaviors: function!) {
S ( t h i s . i d + '__prevBtn') .onclick =
this.previous.bind(this) ;
$(this.id + '_nextBtn').onclick this.next.bind(this);
$(this.id + '_pauseBtn').onclick - this.pause.bind(this);
$ ( t h i s . i d + '_addBtn')-onclick = this.addFeed.bind(this);

, , ,
. ,
Prototype. -, $,
document .getElementByld. -, bind
, onclick .
.
HTML . ,
t h i s . i d .
. , - ,

13 Ajax,

559

13.4.

t h i s . c u r r e n t F e e d RSSFeed,
t h i s . feedlndex

, .
t h i s . o p t i o n s .rssFeeds

t h i s . itemlndex

,
RSSFeed,

, _prevBtn, _nextBtn, _pauseBtn addBtn.


, .
rssReader, , :
<input type="button" id="rssReader_prevBtn" value=" " />
<input type="button" id="rssReader_pauseBtn" value=" I I " />
<input type="button" id="rssReader_nextBtn" value=" " />
<input type="button" id="rssReader_addBtn" value="Add Feed" />
, RSSReader ,
-.
-

. RSS-
,
. ,
. RSS-, , .

, , RSS-.
RSSItems , RSSFeed.
, - , , . 13.4.
, .
( item) RSS-,
.
/ .
, , -.
, , ,
. hasPrevious hasNext 13.31.

IV Ajax

560

... 13.31. has Preyious/has Next


hasPrevious: function() {
return ! (this.feedlndex == 0 && t h i s .iteinlndex == 0);
},

: ,

hasNext: function() {
return !(this.feedlndex == this.options.rssFeeds.length - 1 &&
this.itemlndex == this.currentFeed.items.length - 1 ) ;
},

, .
"" ,
, "" , .
,
. previous (), 13.32.
I

13.32. previous () ^ 1 |
previous: function() {
if ( !this.hasPrevious() ) return;
var requiresLoad = this.itemlndex == 0;
this.fadeOut( this.visibleLayer, Prototype.emptyFunction );
this.visibleLayer = {this.visibleLayer + 1 ) % 2;
if { requiresLoad )
this.loadRSSFeedf this.feedlndex - 1, false );
else
setTimeout( this.previousPartTwo.bind(this),
parselnt (this. options. fadeDuration/4) ). ;

previousPartTwo: function() {
this.itemlndex'; this.updateView();

, previous (),
. , previous () . requiresLoad
true, RSS-, ,
. , . , " ",
. ,
- . , loadRSSFeed(). , , : t r u e , f a l s e
( ) . ,
previousPartTwo() ,
fadeDuration. " " -

13 Ajax,

561

itemlndex updateView (),


.
, ? , : ,
, , ,
. , , ! , {..
), ( ) . , ?
next (), 13.33, , .
next: function{} {
if ( ithis.hasNext() ) return;
var requiresLoad =
this.itemlndex == (this.currentFeed.items.length - 1);
this.fadeOut( this.visibleLayer, Prototype.emptyFunction ) ;
this.visibleLayer = (this.visibleLayer + 1 ) % 2;
if ( requiresLoad >
this.loadRSSFeed{ this.feedlndex + 1, true );
else
setTimeout( this.nextPartTwo.bind(this),
parselnt(this.options.fadeDuration/4) );

nextPartTwo: function() {
this.itemlndex++; this.updateView();

? next ()
, . ,
previous () /next {)
:
this.visibleLayer = (this.visibleLayer + 1) % 2;
, ,
( updateView ()), . ,
HTML-, :
<! >
<div class="content" id="rssReader_content">
<div class="layerl">Layer 0</div>
<div class="layer2">Layer K/div>
</div>
visibleLayer , , div . 0 , -

IV. Ajax

562


0. 1 1.
. , / , -. 13.34
startSlideShow, , , s t a r t ( ) ,
nextSlide ( ) .
3.34. -
startSlideShow: function(resume) {
var delay = resume ? 1 : this.options.slideTransitionDelay;
this.transitionTimer = setTimeout{this.nextSlide.bind(this),
delay);

nextSlide: function{) {
if ( this.hasNextO )
this.next();
else
this.loadRSSFeed(0, true);
this.transitionTimer = setTimeout{
this.nextSlide.bind(this),
this.options.slideTransitionDelay ) ;
),

startSlideShow nextSlide
. , - , slideTransitionDelay, ( ).
nextSlide, next() . , loadRSSFeed(0,true) . . !
, - , .
, 13.35.
riv*i i n i i O . O J . i v ( 1 u a U o c

"^^^1 *i " -
'
.; ^^^

pause: function() {
if ( this.paused )
this.startSlideShow(true);
else
clearTimeout( this.transitionTimer );
this.paused = !this.paused;

pause -.
this.paused.
- , pause s t a r t SlideShow, resume true;

13 Ajax, 563

transitionTimer,
,
.
-, ,
RSS-.
applyButtonBehaviors(), ,
addFeed. (. 13.36) ,
-.
13.36. addFeed
addFeed: function() {
var selectBox = $ ( t h i s . i d + '_newFeeds');
var feedToAdd = selectBox.options[
selectBox.selectedlndex ].value;
this.options.rssFeeds.push(feedToAdd);
},

HTML RSS-. _newsFeeds. addFeed RSS-


t h i s . o p t i o n s . rssFeeds. !
!
, -. , .

, . . , fadeln() fadeOutO,
13 37.
13.37. fadeln< )/fadeOut() |:[:'
fadeln: function( layer, onComplete ) {
this.fadeTo( 0.9999, layer, onComplete );

=|||1|

fadeOut: function( layer, onComplete ) {


this.fadeTo( 0.0001, layer, onComplete );

fadeToO
( ). fadeToO 0 1, 0
, 1 . ,

IV. Ajax

564

13.5. E f f e c t . F a d e T o

t h i s . getLayer ( l a y e r )

DOM
( 0 1)

t h i s . o p t i o n s . f adeDuration
12

{ c o m p l e t e : onComplete}

1 ( 1), , , 1 0,9999.
, , (0
1). , , .
fadeTo() 13.38.
fadeTo: function( n, layer, onComplete ) {
new Effect.FadeTo( this.getLayer(layer),
n,

this.options.fadeDuration,
12,
{complete: onComplete J );

- .
Effect. FadeTo Rico, . Effect.FadeTo . 3.5.
div, , getLayerO,
13.39.

13.39. aetLaverO _ | ^ ^ ^ ^ ^ | ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
getLayer: function(n) {
var contentArea - $(this.id+'_content');
var children = contentArea.childNodes; var j = 0;
for ( var i = 0 ; i < children.length ; i++ } {
if ( children[i].tagName &&
children[i].tagName.toLowerCase() == 'div' ) {
if ( j -~ n ) return children[i];
}
}
return null;

13. Ajax,

565

, ,
_content. ,
n- div.
, . RSS Ajax.
RSS- Ajax
-, DHTML
. Ajax, . , Ajax

DHTML .
,
Ajax, , 13.40 RSS- .
loadRSSFeed: function{feedlndex, forward) {
thxs.feedlndex = feedlndex;
this.iteralndex = forward ? 0 : " l a s t " ;
new net.ContentLoader(this,
this.options.rssFeeds[feedlndex],
"GET", [] ).sendRequest();
),

net.ContentLoader
Ajax, URL RSS-,
t h i s . o p t i o n s . r s s F e e d s . forward , , ( ) . ,
, itemlndex. , , , itemlndex ,
l a s t , . ,
itemlndex RSS-. ,
, , .
, net.ContentLoader
ajaxUpdate handleError. aj axUpdate, 13.41, ,
.

IV. Ajax

566

13.41. *1^^
aj axUpdate: function(request) {
if ( window.netscape Sfi
window.netscape.security.PrivilegeManager.enablePrivilege)
netscape.security.PrivilegeManager.enablePrivilege(
'UniversalBrowserRead') ;
this.currentFeed =
RSSFeed.parseXML(request.responseXML.documentElement);
if ( this-itemlndex == "last" )
this.itemlndex = this.currentFeed.items.length - 1;
this.updateView();

__L

ajaxUpdate , ,
PrivilegeManager. ,
UniversalBrowserRead. , ,
Mozilla.
t h i s . c u r r e n t F e e d RSSFeed, "".
RSSFeed, Ajax. this.itemlndex l a s t (
loadRSSFeed ), itemlndex
RSSFeed. , updateView() .
, handleError (
, net.ContentLoader,
, - ). RSS , ,
handleError. , ( ) .
handleError: function(request) {
this.getLayer(this.visibleLayer).innerHTML =
this.options.errorHTML;

, Ajax
RSSReader, ,
.

, ,
. , , , , . . , , updateView () ( 13.42), .

13. Ajax, 567

13.42. updateViewf)
updateView: function() {
var rssItemView new RSSItemView(
this.currentFeed.items[this.itemlndex],
this.feedlndex,
this.itemlndex,
this.options.rssFeeds.length )j
this.getLayer(this.visibleLayer).innerHTML = rssItemView;
this.fadeln( this.visibleLayer,
this.bringVisibleLayerToTop.bind(this) );

, updateview()
, innerHTML ( ). . .
, ,
bringVisibleLayerToTop.
z Index, , . bringVisibleLayerToTop () :
bringVisibleLayerToTop: function() {
this.getLayer(this.visibleLayer).style.zlndex = 10;
this.getLayer((this.visibleLayer+1)%2).style.zlndex = 5;
}
,
. ,
, .

13.7.4.
, MVC- RSS-. RSSFeed, RSS-,
, RSSItem.
RSSItem RSSFeed
RSSItemView. ,
RSSReader,
- .

13.8.

__

Ajax , , . XML- , . -

>68

IV. Ajax

HTML- CSS,
. DHTML,
> , , ,
. Ajax, RSS- Web-. ,
XML-. ,
CML , , Web-. ,
; "--" (MVC),
.

572

V.

Ajax .
. , Ajax , Web-,
Web- ( , - Web-, ).
, .
(Integrated Development Environment IDE) Ajax ,
, , . , Ajax-. ,
.

.

. "" ,


. , ,
.
, . , :
" , ,
".
,
. , , , ,
Ajax.

.1.1.

, . , Ajax, , Web-, JavaScript,
HTML CSS.

. Ajax

573

1, Ajax ,
Web-, , .
Ajax , ( ),

. ,
JavaScript-, Ajax, , JavaScript (
3).
Web- Ajax . -, ,
Ajax- . -, JavaScript
,
.
,
, . ,
(, IDE),
, JavaScript.
, Ajax, ,
. , , .
, , (plug-in). , IDE
Web-, - . ,
, ,
, , , . Eclipse IDE, ,
Java-,
Ajax, Firefox, (
), , Web-.
Eclipse Firefox , , - . , Web- , .
.

574

V.

.1.2.
. IDE .
, , Ajax
IDE!
Unix , .
, ,
.
, JavaScript- 7,
, .3.4.
, JavaScript, Ajax , . ,
, "" JavaScript (. 6).
, .NET, Java
. , HTTP, .3.3.
.
Web- , .
, IDE Eclipse Web Firefox. Eclipse , ,
. , ,
, , , ,
.
Ajax-
. ; .
,

.1.3.
, Ajax ,
Java NET, Eclipse, NetBeans Visual Studio.
, .
IDE , ,
, , , ,
, .

. Ajax

575

, . ,
.

.2. IDE
, , Notepad ()
, . JavaScript, HTML CSS
, , # , Visual Basic Java, , . , ,
.

.2.1.
, , . . - ; . Ajax (.. HTML, CSS JavaScript)
, .
Web, Ajax
, . ,
, .

,
. Ajax ,
,
( Windows Notepad), .
, , .

,
,
. ,
, , , .


; - .
Ajax . HTML. CSS, XML JavaScript ( ), , ( )
: Java, C # , VB ASP, PHP JSP
( "" HTML-). ,
,
Ajax, .

,
, .
, , , , ( ), , ,

. ,
.



, , .
, , Ajax, ,
.
.
,
Web- Web- ( ,
). ,
,
-.

" " .
,
, ,

. Ajax

Ajax, !
.
.
:
, Ajax
Web- ?
JavaScript, ,
Ajax-
.

,
, ,
, .
, , ]
,
. !
, .

Web- WYSIWYG-
Web-. , Ajax DOM. HTML- .
Ajax- , , , .
, ,
JavaScript DOM.

.2.2.
Ajax .
,
.


, -,
.
TextPad, Notepad2, EditPlus, Unix
Vim Emacs, jEdit, -, . JavaScript . .

. .1. , JavaScript ( ):
TextPad, Gvim jEdit

TextPad }' , CSS, JavaScript, XML


HTML, .
(, ). TextPad Microsoft Windows.
NotePad2 EditPlus.
jEdit Java;
, . 100 , ?
Aj-.
, .
, jEdit. ,
, , , CSS XSLT.

. .2. JavaScript- Eclipse


JavaScript,
-

Vim Emacs , Unix (


Windows-). JavaScript-.

, .NET Java, . ,
. , ,
, Ajax.
Microsoft Visual
Studio, Web- Visual InterDev, JavaScript CSS. He (Visual Studio Express), , Web-.
IDE Java- Eclipse, IBM, ,
Java- , Java-. JavaScript-,
(. .2).
Eclipse 3.1 ( Web Tools Platform) Web-; J2EE, JavaScript, XML,
HTML CSS. , Eclipse

580

CVS. , Subversion. Visual SourceSafe .


Java-, Sun Java
Studio Creator SAP NetWeaver. Web- . , ,

Web-, , Ajax. ,
Studio Creator Java ServerFaces (JSF), Ajax 5,
, , ,
JSF, Ajax.
Ajax ,
Web-, . Macromedia Dreamweaver Microsoft FrontPage, , Ajax.
Dreamweaver JavaScript- CSS- (. .) HTML-
,
WYSIWYG- JavaScript,
.
Dreamweaver FrontPage (, . Prototype Rico) , - .
Komodo (ActiveState)
(Perl, Python, PHP, Tel, JavaScript
XSLT) . Komodo JavaScript ; , ,
JavaScript (. .4). ,
JavaScript, . Ajax. Komodo . , :
Komodo XML
XUL, Web- Firefox.

.

A 3 .
,
. ,

. .. Dreamweaver JavaScript CSS


CSS;

. .4. Komodo
JavaScript
,
, O b j e c t V i e w e r

582


, , .

3.1
, . ,
, Ajax-.
'""
, ,
JavaScript-
Ajax-. , - Ajax- . ,
HTTP-. JavaScript.

.3.2. JavaScript
JavaScript- -
. , # Java, ,
, , .
JavaScript- ,
. , .

,
. , ,
.
JavaScript
, debugger. , , :
var x=3;
var y=x*7,debugger;
var z=x+y;

(. .5) , .
. z ,
, "" .

. .5. d e b u g g e r
(JavaScript)

, . ,
.

JavaScript ,
. , , , .
:
function doASum(){
var a=3;
var b=4;
var c=multiply(a-2,b+6);
return {a+b)/c; }
function multiply(varl,var2){
var nl=parseFloat(varl);
var n2=parseFloat(var2);
debugger;
return nl*n2; }

nl, n2, v a r l var2. ,


, , . , , b
doASum().
doASum() ,
. ,
doASumO ,
multiply () (. .6).
,
- .


, . -

. .6. Mozilla Venkman


,

. Ajax

585

, , -
, , .
.
for (var i=0;i<100;i++){
var divisor=i-57;
debugger;
var val=42/divisor;
plotOnGraphfi,val);
}

"", , . .
for (var i=0;i<100;i++){
var divisor=i-57;
if (divisor^=0){ debugger; }
var val=42/divisor;
plotOnGraph(i,val);
}
,
. , ..
.
, .
, IDE ,
(. .7).
,
, true.

. , , ,
.
,
(. .8). ,
, , ,
, .
1, .
JavaScript-. Venkman Mozilla Firefox Microsoft Script
Debugger { , "") Internet Explorer.
Venkman , , 7.
Microsoft Script Debugger

. .7. Mozilla Venkman

. .8.
Mozilla Venkman

" " JavaScript-


( ,
).
Visual Studio Komodo JavaScript .

JavaScript- ,
. Java .NET . -

. .. Mozilla LiveHTTPHeaders
HTTP-

Eclipse Visual Studio ( IDE)


. Web-, Java, JBoss Eclipse,
Web-.
Visual Studio, Web-, Web- ASP.NET. , Visual Studio
,
.
, .
,
, . .

.3.3. HTTP
Ajax Web-
HTTP. .
HTTP-, , ,
, .
Live HTTP Header
Mozilla Firefox LiveHTTPHeaders,
HTTP-, (. .9). ,
, Ajax. ,
GET POST ( ).
LiveHTTPHeaders .
Firefox (, Modify Headers), .

588

V.

Fiddler
Microsoft Research Fiddler, .NET , LiveHTTPHeaders, , JavaScript.
,
.
LiveHTTPHeaders, , Fiddler ,
.
Web-.
Charles
Charles - , Java.
Fiddler, .
( , ), . ,

, ,
.
, . Charles Fiddler ,
,
, Ethereal Apache TCPMon.
. , JavaScript-
HTTP ,
,
.
.
, . , Iog4j Java
Apache, , , JavaScript . ,
JavaScript,
.

.3.4. ,

, .
1
, .

. Ajax

589

Web- JavaScript .
( JavaScript Mozilla , ,
.)
, , . , . - JavaScript,
, . ,
. HTML- . ,
.
DOM
.
. DOM .
Console=ftmction(el){
this.el=document.getElementByld(el);
this.el.className='console 1 ;
this.el.consoleModel=this;
this.clear();
I
, , DOM,
CSS.
Console.prototype.append=function(obj,style){
var domEl=styling.toDOMElement(obj);
if (style) {
domEl.classKame=style;
}
this.el.appendChild(domEl);
}

toDOMElement () ,
DOM.
DOM, ,
, div.
styling.toDOMElement=function(obj){
var result=null;
if (obj instanceof Element){
result=obj;
}else{
var txtNode=document.createTextNode(String(obj));
var wrapper=document.createElement('div') ;
wrapper.appendChild(txtNode);
result=wrapper;
}
return result;
}

590

,
.
Console.prototype.clear=function{)f
while(this.el.firstChild){
this.el.removeChild{this.el.firstChild);
}
}

, . ,
ObjectViewer (. 4 5).
DOM, .
<div id= 1 console'x/div>
CSS,
.
div.console {
position .-absolute;
I
top:32px;
/
left:600px;
width:;
height:500px;
overflow:auto;
border: lpx s o l i d black;
b a c k g r o u n d - c o l o r : #eefOff;

;
Ajax.
.
.
var logger=null;
window.onload=function(){
logger=new Console{"console");
logger.append{"starting planets app");
}

window.onload, DOM . ,
. logger .append()
planets.Planet=function
(id,system,name,distance,diameter,image){
this.id=id;
logger.append("created planet object ' "+this.name+"'");
}
ObjectViewer ( tentLoader) , -

. .10. ,
, .
, ,
moons . x m l

, ..,
. ,
, , .
net.ContentLoader.prototype.defaultError=function(){
logger.append("network e r r o r ! " + t h i s . u r l , "urgent");
}
. Object Viewer.
,
Ajax. , Iog4] (Apache).
,
.
DOM.

4.
Ajax DOM. JavaScript-,
DOM. ,
, .
DOM , . , , DOM ,

. .11. DOM Inspector Mozilla


DOM Web-, , , HTML-

, ,,; ,
DOM, , ,
, , DOM.
DOM , .
, Mozilla Firefox, . ,
Internet Explorer.

.4.1. DOM Inspector Mozilla


DOM Inspector Firefox,
.
, Tools () DOM
Inspector. DOM Inspector
(. .11)-
,
HTML. , ,
, HTML- , , . CSS,
.
, . , ( ).
Search => Select Element Click DOM Inspector, Web- ,
. (
.)

, DOM,
CSS, JavaScript (. 12).

Ajax

593

. .12. DOM Inspector (Mozilla) DOM


t a r g e t DOM,
; ,

, Evaluate JavaScript.
(target) DOM, , , , t a r g e t . s t y l e . border='4px
solid blue'.
DOM Inspector ,
. (. . 13). ,
URL inspect,
DOM
.

.4.2. DOM Internet Explorer


Mozilla , DOM
Internet Explorer. , , . ,
, IEDocMon ( 1
" ').
Mozilla DOM Inspector, IEDocMon DOM, (. .13).
,
Ajax-. Ajax ,
Firefox. ,
Firefox.

. .13.
lEDocMon Internet Explorer
,
DOM Inspector (Firefox)



14.3. Safari DOM Inspector Mac OS X


> Safari Mac OS X DOM,
. '. , Terminal defaults w r i t e com.apple.Safari IncludeDebugMenu 1. , , sudo.
Safari,
.

1.5. Firefox
1 Firefox:
^enkman LiveHTTPHeaders. , Firefox. Web
Firefox, Modify Headers.
Firefox . ;
ttps://addons .mozilla.org/extensions. . .14 ,
Modify Headers
Mozilla Update.

I n s t a l l Now. ( .15).

. .14.
Firefox

. .15.
Firefox

,

JavaScript-
. ,
. ,
.
Extensions (. .16).
Firefox ( DOM, ..) Firefox. Tools (. .17).
Firefox ,
Web-.
addons.mozilla.org,
. ( Venkman) .

596

V.

. .16.
E x t e n s i o n s

. .17.

1.6.
. , ,
Web-:
Textpad (www.textpad.com);
jEdit ( w w w . j e d i t . o r g ) ;
Eclipse (www.eclipse.org);
JavaScript Eclipse ( h t t p : / / j s e d i t o r . s o u r c e f o r g e . n e t / ) ;
Visual Studio Express ( h t t p : / / l a b . m s d n . m i c r o s o f t . c o m / e x p r e s s / ) ;
Dreamweaver (www.macromedia.com/software/dreamweaver/);
Komodo (www.activestate.com/Products/Komodo/);
Venkman Debugger ( w w w . m o z i l l a . o r g / p r o j e c t s / v e n k m a n / ) ;
Microsoft Script (www. m i c r o s o f t , c o m / d o w n l o a d s / d e t a i l s . aspx?
F a m i l y i D = 2 f 4 65be0-94fd-45 6 9 - b 3 c 4 - d f f d f l 9 c c d 9 9 & d i s p l a y l a n g = e n ) ;
Charles (www.xk72 . c o m / c h a r l e s / ) ;
Fiddler (www.fiddlertool.com);
LiveHttpHeaders ( h t t p : / / l i v e h t t p h e a d e r s . m o z d e v . o r g / ) ;
Modify Headers ( h t t p s : / / a d d o n s , m o z i l l a . o r g / e x t e n s i o n s /
moreinfo.php?id=967&vid=4243),
D O M Internet Explorer IEDocMon (www.cheztabor.com/
IEDocMon/index. htm).
/'

198

V.

JavaScript .
, .
JavaScript;
: .
, ,
Java # , JavaScript. ( , C + + . ,
C + + , ,
, JavaScript .)
1 - ,
JavaScript, Java # ,
, . ,
.
JavaScript , Java # .
. ,
, .
, Java C + + , I, ,
^ .

11. JavaScript Java


? Java JavaScript
. JavaScript , . Netscape
livescript.
, JavaScript .
, Scheme Self;
1 Python. JavaScript Java, -
. JavaScript Java,
.
1. JavaScript , ^ Lisp.
, ,
.
[, ,
"1' .

. Ajax

599

.1. Java JavaScript

,
, .
JavaScript

.

. JavaScript
, Java, #.
Ajax- .
,
,

JavaScript

Java
. JavaScript
,

JavaScript
Java, C++ #
, .
.
JavaScript
. JavaScript ,
Java, ,

, . ,
(, , ).
: , ,
, , . JavaScript Java, ,
.
, ,
JavaScript,
JavaScript.

.2. JavaScript

__

JavaScript,
. , .

; ,
.

600

V.

JavaScript ,
Object.
var myObject=new Object();

.2.2 ,
> new. myObject '''',
:.. . ; ,
.

5.2.1
< , JavaScript 1 , .
i . , , ) "" .
. ,
.
.
> JavaScript.
, JSON.
, JavaScript.
JavaScript
[ . JavaScript , =.
'.
myObject.shoeSize="12";

shoesize.
. JavaScript -.
, ,
, . ,
.
myObject['shoeSize']="12";
, .
> , ,
. .2.4.
.
myObject.speakYourShoeSize=function(){
alert{"shoe size : "+this.shoeSize);
}
* '

. Ajax

601

,
.
function sayHello(){
alert ('hello, my shoeSize is '-f-this. shoeSize);

myObject.sayHello=sayHello;

, , ,
. , , sayHello() myObject
, , n u l l .
myObject.sayHello=sayHello() ;

,
.
var myLibrary=new Object();
myLibrary.books=new Arrayf);
myLibrary.books[0]=new Object();
myLibrary.bookstO].title="Turnip Cultivation through the Ages";
myLibrary.books[0].authors=new Array();
var jim=new ObjectO;
jim.name="Jim Brown";
jim.age=9;
myLibrary.books[0].authors[0]=jim;

. ,
JavaScript , JSON . .
JSON
JavaScript Object Notation (JSON) ,
. JSON, JavaScript,
.
JavaScript Array.
new.
myLibrary.books=new Array();
, Java.
myLibrary.books[4]=somePredefinedBook;

, Java MapPython Dictionary . , JavaScript.


myLibrary.books["Bestseller"]=somePredefinedBook;

,

. -

V.

602

: , .
myLibrary.books=[predefinedBookl,predefinedBook2,predefinedBook3] ;
JavaScript ;
:.
myLibrary.books={
b e s t s e l l e r : predefinedBookl,
cookbook : predefinedBook2,
spaceFiller : predefinedBook3
};
, , . . ,
JSON, . :
"Best Seller" : predefinedBookl,
JSON- .
( ).
var myLibrary={
--'
location : "my house",
keywords : [ "root vegetables", "turnip", "tedium" ],
books: [
{
title : "Turnip Cultivation through the Ages",
authors : [
{ name: "Jim Brown", age: 9 },
{ name: "Dick Turnip", age: 312 }

publicationDate : "long ago"

);

title : "Turnip Cultivation through the Ages, vol. 2",


authors : [
{ name: "Jim Brown", age: 35 }
],
p u b l i c a t i o n D a t e : new Date(1605,11,05)

myLibrary : l o c a t i o n
; keywords ; books .
, books, (),
( JavaScript- Date,
) (). name age. JSON
.
( ).
, , ,

Ajax

603

JavaScript- Date.
JavaScript,
.
function gunpowderPlot(){
return new Date(1605,11,05);
}
var volNum=2;
var turnipVol2={
title : "Turnip Cultivation through the Ages, vol. " +volNum,
authors : [
{ name: "Jim Brown", age: 35 }

h
publicationDate : gunpowderPlot()
}

};

, publicationDate , .
gunpowderPlot (), .
- , JSON, ,
.
var turnipVol2={
t i t l e : "Turnip Cultivation through the Ages, vol. "+volNum,
authors : [
{ name: "Jim Brown", age: 35 }

publicationDate : gunpowderPlot()
}
],
summarize:function(len)(
if (!len){ len=7; }
var summary=this.title+" by " +this.authors[0].name
+" and his cronies is very boring. Z";
for (var i=0;i<len;i++){
summary+="z";
}
alert(summary);
}
};
turnipVol2.summarize{6);

summarize*)
JavaScript; , t h i s .
JavaScript-, JSON,
JavaScript. , JavaScript
, JSON.

604

V.

v a r numbers={ o n e : 1 , t w o : 2 , t h r e e : 3
numbers.five=5;

, JSON, , JavaScript.
JSON ,
JavaScript.
var cookbook=new Object();
cookbook.pageCount=321;
cookbook.author={
firstName: "Harry",
secondName: "Christmas",
birthdate: new Date(1900,2,29),
interests:
["cheese","whistling",
"history of lighthouse keeping"]
};

JavaScript- Object Array JSON, .


JavaScript , ,
. ,
.

S.2.2. -,
3 - , . Java,
i JavaScript new, : . .
Java , (
"), java.lang.Object.
,
lava. ,
^ , , .
MyObject myObj=new MyObject{argl,arg2);
,
lyObject .
JavaScript , . JavaScript 1 ,
i .
.
MyJavaScriptObj ect.completelyNewProperty="something";

.
[, . .
JavaScript, -

. Ajax

605

, . ,
,
.
JavaScript , Java-.
var myObj=new MyObject();
MyObject
. .
function MyObject(name,size){
t h i s . name=naine;
this.size=size;
}

:
var myObj=new MyObject("tiddles","7.5 meters");
alert("size of "+myObj.name+" is "+myObj.size);

t h i s , , . a l e r t (), t i d d l e s .
.
function MyObject{name,size){
this.name=name;
this.size=size;
this.tellSize=function(){
alert("size of "+this.name+" is "+this.size);
}
}
v a r myObj=new O b j e c t ( " t i d d l e s " , " 7 . 5 m e t e r s " ) ;
myObj.tellSizet);

, .
-, MyObject . , , , , . -,
, (closure).
, , DOM, . .
, .
JavaScript-, . . new , new . ,
.
function MyObject{name,size){
this.name=name;
this.size=size;

V.

>06

>
MyObject.prototype.tellSize=function(){
alert("size of "+this.name+" is "+this.size);

J
var myObj=new MyObject{"tiddles","7.5 meters");
myObj.tellSize();

, . .
: t h i s
.
.
, . ,
. .
, .
MyOb j ect.prototype.color="red";
var objl=new MyObject();
MyObj e c t . p r o t o t y p e . c o l o r = " b l u e " ;
MyObject.prototype.soundEffect="boOOOoing!!";
v a r obj2=new M y O b j e c t { ) ;

obj 1 ,
. ob j 2 , , 1 : .
. , , ,
avaScript- .
, , ..
JavaScript,
(host
bject)). , .

2.3.
JavaScript ,
, , , , C + + Java.
. , , . . Internet Explorer DOM-;
< ,
' Array .
Array.prototype.indexOf=function(obj){
var r e s u l t = - l ;
for (var i=O;i<this.length;i++){
if (this[i]==obj){

. Ajax

607

result=i;
break;
}
}
return result;
}

Array ,
-1,
. , ,
.
Array.prototype.contains=function{obj){
return (this.indexOf(obj)>=0);
}
, ,
, .
Array.prototype.append=function(obj,nodup){
if (!(nodup && this.contains(obj)))f
this[this.length]=obj;
}
}
,
Array, ,
new JSON.
var numbers=[l,2,3,4,5];
var got8=numbers.contains(8);
numbers.append("cheese",true);
, , ,
, ,
. , .
, ;
, .

Ajax-. , ,
. C + + , Java # , JavaScript , . .

.2.4.
, .
Shape, .
, .

V.

608

. , . public,
p r i v a t e p r ot e c t e d .
. , JavaScript . , ,
.
( ) , JavaScript , .
, , , .
, ,
,
, .
, ,
Java- Struts Tapestry. , . ,
, Web- .
.
,
. ,
JavaScript .
JavaScript, .

.2.5. JavaScript-
, . .
- , . , , .
. , Java .NET.
, JavaScript- , .
if (MyObject.someProperty){
}

. Ajax

609

, MyObject.someProperty
false, 0, null, if
. :
if (typeof(MyObject.someProperty) ! = "undefined"){
, i n stanceof, ,
if (myObj instanceof Array){
}else if (myObj instanceof Object){
}

, .
if (myObj instanceof MyObject){

}
instanceof ,
. -, , JSON, Object, Array. -, "". , Function Array Object, .
, Array:
function testType(myObj){
if {myObj instanceof Array){
alert{"it's an array");
}else if {myObj instanceof Object){
alert("it's an object");
}
}
testType([l,2,3,4J);

, Array.
.
.
function testType(myObj){
if (myObj instanceof Object){
a l e r t ( " i t ' s an o b j e c t " ) ;
}else if (myObj instanceof Array){
a l e r t ( " i t ' s an a r r a y " ) ;
}
}
testType([l,2,3,4]);
,
Object. .
, . for.

610

V.
f u n c t i o n MyObject(){
this.color='red1 ;
this.flavor-'strawberry' ;
this.azimuth='45 degrees';
this.favoriteDog1collie1;
}
v a r my0bj=new M y O b j e c t O ;
var debug="discovering...\n";
f o r ( v a r i i n myObj){
debug+=i+" -> "+myObj[i]+"\n";
}
alert(debug);

,
, . , D0M .
5 6
ObjectViewer.
- ,
, .

.2.6.
, , . Shape,
, .. ,

. Shape .
.
C + + Java . "" . , .
, , Shape, .
, , .
Ajax-. JavaScript
, .
, , . (Dave
Thomas) (duck typing):
, , .

. Ajax

611

Shape, , ,
.
, . Java, :
public double addAreas{Shape s i , Shape s2){
return si.getArea()+s2.getArea();
}
- , , , ,
. JavaScript
, .
function addAreas(sl,s2) {
return si.getArea()+s2.getArea{);
}
, ,
getArea (), JavaScript . , .
function hasArea(obj){
return obj && obj.getArea && obj.getArea instanceof Function;
}
.
function addAreas(si,s2){
var t o t a l = n u l l ;
if (hasArea(sl) && hasArea(s2)){
total-sl.getArea()+s2.getArea();
}
return total;
}

JavaScript,
, , .
function implements(obj,funcName){
return obj && obj[funcName] && obj[funcName] instanceof Function;
}
Object.
Obj ect.prototype.implements=function{funcName){
return this && this[funcName] && this[funcName] instanceof Function,
}

.
function hasArea(obj){
return obj.implements("getArea");
}

612

V.
function isShape(obj){
r e t u r n obj.implements("getArea") && o b j . i m p l e m e n t s ( " g e t P e r i m e t e r " ) ;
}

,
, Java. , getAreaO, , , . , JavaScript-,
, . ( , , , ,
.)
.
.
function isNum(arg){
return parseFloat(arg)!=NaN;
}

NaN "not a number" (" "). JavaScript, . t r u e ,


. parseFloat p a r s e l n t O .
parseFloat("64 h e c t a r e s " ) 64, NaN.
addAreas {).
function addAreas(si,s2){
var t o t a l = n u l l ;
if (hasArea(sl) && hasArea(s2)){
var al=sl.getAreaf); var a2=s2.getArea();
if {isNum(al) && isNum(a2)){total=parseFloat(al)+parseFloat(a2);
}
}
return t o t a l ;
}
parseFloat ( ) . ,
, . si 32, a s2 64 hectares, addAreas ()
96. parseFloat () , 3264 hectares!
, : ,
,
. ,
. , ,
, .
"" , , , .
JavaScript .
.

. Ajax

..

613

__

, , . ,
Java # , , JavaScript
, .
,
.

.3.1.
Java- ,
. JavaScript Java . Java- , , .
JavaScript ,
. ( Java-
.)
, , ,
JavaScript , C + + .
, .
JavaScript Function . ,
, Object
, JavaScript, . Function
Function ( ).
, Function.
, .
var
result=MyObject.doSomething(x,, z)

Function , c a l l ( ) ( apply (), ).


var result=MyObj ect.doSomething.call(MyOtherObject, x, y, z)
:
var result=MyObject['doSomething1].call(MyOtherObject,x,,z)

Function.call{) ,
. . apply () -, ,
, .
.
, JavaScript . Java # , ,
. JavaScript -

614

V.

undefined.
arguments
.
. , get- set-.
function area(value){
if (value){
this.area=value;
}
return this.area;
}

{) , value , get. , set-.


(.
3). ,
.
, , .

5.3.2.
JavaScript ,
, :
function doSomething(x,,z){

...

.
var doSomething=function(,,z){

...

, JavaScript
[ .
| Java # . .
( , ,
).
myObj.doSomethingNew=doSomething;
myObj.doSomethingNew(x,y,z);

, , . , ( , )
(. .2.2) .
, .

. Ajax

615

.3.3.

.
, ; , Ajax-.
? . , .
function Tree(name, leaf, bark){
this.name=name;
this.leaf=leaf;
this.bark=bark;
}
, .
Tree.prototype.describe=function(){
return this.name+": leaf="+this.leaf+", bark="+this.bark;
}
Tree ,
.
var Beech=new Tree("green, serrated edge","smooth");
alert{Beech.describe());
Beech: leaf=green, s e r r a t e d edge, bark=smooth. .
, .
function Dog(name,bark){
this.name=name;
this.bark=bark;
}

Dog.
var Snowy=new Dog("snowy","wau! wau!");
,
( ), , , .
Tree.
var tmpFunc=Beech.describe;
tmpFunc.call(Snowy);

, , f u n c t i o n . c a l l ( ) ,
, t h i s .
, Snowy: leaf=undefined, bark=wau! wau!.
, , .
?
, ?
: . -

516

V.

Tree
,
lyTree.describe (). ,
, . t h i s
. .
; , .
, Snowy b a r k ( ) .
, ,
.

13.4. Ajax-

) Ajax- , . 4, ,
[ , .
onclick;
.
DHTML , ;
[ ,
.
[TML-, :
<div id='rayDiv' o n c l i c k = ' a l e r t : a l e r t ( t h i s . i d ) ' x / d i v >
.
function clickHandler(){ a l e r t ( t h i s . i d ) ; }
myDiv.onclick=clickHandler;
, Funcion ( clickHandler ).
> HTML- .
< .
myDiv.onclick=function{){ a l e r t ( t h i s . i d ) ; }
, :
. tf DOM,
5 Event, . ,
, . , DOM
- ,
^ .
. -

. Ajax

617

,
, DOM .
function myObj(id,div){
this.id=id;
this.div=div;
this.div.onclick=this.clickHandler;
}

DOM, . :
myObj.prototype.clickHandler=function(event){
alert(this.id);
}
, ,
, ? , myObj .clickHandler () (
, ),
, . , , ,
.
.
, ,
-.
. , , , , .
, .


, . DOM,
,
. . .1.
, , ,
. , , , Web-,
.
,
myObj,
,
myObj.foo{).
.
var MyObjects=new Array();

, ,
:

. .18. .
,

function myObj(id){
this.uid=id;
MyObjects[this.uid]=this;
this.render();

^S

myObj. ! .
myObj.prototype.f00=function(){
alert('foooo!M f +this.uid);
}

render () DOM.
myObj.prototype.render-function(){
this.body=docuraent.createElement("div");
this.body.id=this.uid+"_body";

this.titleBar=document.createElement("div");
this.titleBar.id=this.uid+"_titleBar";
this.titleBar.onclick=fooEventHandler;
}

DOM- ,
, .
, f ooEventHandler ()
onclick DOM, -.
function fooEventHandler(event){
var modelObj=getMyObj(this.id);
if (modelObj){ modelObj.foo(); } }}

. .19.
DOM

f (), myob j. .
function getMyObj(id){
var k e y - i d . s p l i t ( _ " ) [ 0 ] ;
r e t u r n MyObjectsfkey];

id DOM- ,
,
.
, , DOM .
( , . ,
,
Mozilla DOM Inspector.)
DOM
DOM, , . (. .2).
. , f () , .
DOM, JavaScript, ,
, .
myObj.prototype.createView=function(){
this.body=document.createElement("div");

V.

620

this.body.modelObj=thi s;
this.titleBar=document.createElement("div");
this.titleBar.modelObj=this;
this.titleBar.onclick=fooEventHandler;
}

.
function fooEventHandler(event){
var modelObj=this.modelObj;
if (modelObj){ modelObj.foo(); }
}
}

.
, , . DOM-
, DOM.
" ".
,
, 7,
DOM-.
, JavaScript , ,
. , , .
JavaScript, , . Java # , ,
Groovy Boo, . # 2.0. , .

S.3.5. JavaScript
Function , , (
). Function,
, .
JavaScript . ,
new ClosureO, .
(, ) - .
, . , ,

. Ajax

621

, , .
, .
function Robot(){
var createTime=new Date();
this.getAge=function{){
var now=new Date();
var age=now-createTime;
return age;
}
}
( , - .) , createTime ,
, , , (
).
this.createTime=new Date{);

getAge (
, c r e a t e Time, . , .
, 10-50
.
var robbie=new Robot();
window.onload=function(){
alert(robbie.getAge());
}

createTime
, " "
, robbie Robot. ,
.
, . ,
getAge () ,
Robot.
function Robot(){
var createTime=new Date();
this.getAge=roboAge;
}
function roboAge{){
var now=new Date{);
var age=now-createTime;
return age;
};

,
createTime .

V.

122

, ,
. , " " . DOM, .

, ,
. .3.4, ,
, . DOM .
DOM-. .
myOb j.prototype.createView=function(){
this.titleBar=docuroent.createElement("div"};
var modelObj=this;
this.titleBar.onclick=function(){
fooEventHandler.call(modelObj);
}
}


modelObj.
modelObj . , ; t h i s .
2
ontentLoader. onreadystatechange, Internet Explorer,
indow. window , ,
ContentLoader readyState.
, .
, Ajax, .
, . Robot .
function Robot(){
this.createTirae=new Date{);
}
Robot.prototype.getAge=function(){
var now=new Date();
var age=now-this.createTime;
return age;

getAgeO , , , Robot .

. Ajax

623

, .
, (Jim
Ley), .

.4.

JavaScript. . -, . -, ,
. , ,
.
JavaScript
Object Array, JavaScript: JSON, . , , JavaScript
- , . , ,
.
JavaScript- Function, , , .
, . , JavaScript. ,
, , .
Java # , JavaScript
. , ,
, , .
JavaScript . , .
JavaScript, . ,
Ajax , .

.5.
, JavaScript,
Web-, . (David Flanagan) JavaScript: The Definitive Guide (O'Reilly, 2001) ,

624

V.

. ,
. (Nicholas Zakas) Professional
JavaScript for Web Developers (Wrox, 2004) , , .
JavaScript, 2- . , .
Web. (Doug Crockford) JavaScript, ,
(http://www.crockford.com/javascript/private.html) (http://www.crockford.com/javascript/private.html).
- (Peter-Paul Koch) http://quirksmode.
.
(Jim Ley) JavaScript
http://jibbering.com/faq/faq_notes/closures.html.
h t t p : //www. c r o s s browser .com.

626

V.

Ajax JavaScript
.
,
.
;
. ,
,
. ,
, , .
, ! Ajax,
. ; ,
. !
Accesskey Underlining Library

www.gerv.net/software/aul/

<>. DOM accesskey JavaScript.
Act iveWid gets
;
www.activewidgets.com
JavaScript; .
Ajax JavaServer Faces Framework
(Apache)
http://smirnov.org,ru/en/ajax-jsf.html
JavaServer
Faces Ajax.
Ajax. MyFaces. JSF .
Ajax JSP Tag Library

http://ajaxtags.sourceforge.net/
JSP,
Asynchronous JavaScript and XML (Ajax) JavaServer
Pages. ,

. Ajax

627

J2EE JavaScript-
Web- Ajax.
Autocomplete , , , . Callout , HTML onclick. Select
, , . Toggle
t r u e false, . update Field
, ,
.
Ajax.NET

(Michael Schwarz), 2005


,
http://weblogs.asp.net/mschwarz/
, JavaScript-
.NET. JavaScript .NET JavaScript. JavaScript-. .
. ,
JavaScript-,
( DataTable, D a t a S e t , DataView, Arrays Collections).

AjaxAC

(Apache 2.0)
http://ajax.zervaas.com.au
, JavaScript ( ).
(HTML-) . , JavaScript-
HTML-. HTML-
JavaScript-, .
AjaxAC MySQL
. JavaScript- (, ,
).

628

V.

\jaxAspects


ittp://ajaxaspects.blogspot.com
, JavaScript
Web-. SOAP WSDL.
KML. , .
^jaxCaller
(Michael Mahemoff), 2005

ittp://ajaxify.com/run/testAjaxCaller
XMLHttpRequest. Ajax. ; -; "" AjaxPatterns. REST.
AJaxFaces
(ASF)
http://myfaces.apache,org/
JavaServer Faces Ajax
Apache.
BackBase

http://www.backbase.com
, , .NET- Java. BackBase (Rich Internet Application), , . BackBase,
Web- . BackBase
XHTML.
Behaviour
(Ben Nolan), 2005

www.ripcord..nz/behaviour/

Behaviour CSS JavaScript- DOM. -

. Ajax 629

CSS, JavaScript (, onclick).


DOM,
JavaScript. ,
(.. ,
, ). Behaviour ,
onclick ,
.
JavaScript-.
Bindows

www.bindows.net

(Software Development Kit SDK),
-,
, DHTML, JavaScript, CSS XML. Bindows
,
( Java, Flash ActiveX ). Bindows ,
XML, SOAP XML-RPC.
BlueShoes
;
www.blueshoes.org
, WYSIWYG
.


http://cakephp.org/
Ruby on Rails PHP
Ajax.
CL-Ajax
(Richard Newman), 2005

http://cliki.net/cl-ajax
JavaScript Lisp;
JavaScript; JavaScript
DOM; SAJAX.

30

V.

omfortASP.NET
;
ww.daniel-zeiss.de/ComfortASP/
[ , ASP.NET Ajax.
ComfortASP.NET Ajax (DHTML,
avaScript, XML, HTTP), Web-
.SP.NET.
oolest DHTML Calendar

ww.dynarch.com/projects/calendar/
[ - JavaScript;
, CSS.
;PAINT

3ross-Platform Asynchronous Interface Toolkit)


(GPL LGPL)
ttp://cpaint.sourceforge.net
" Ajax JSRS (JavaScript Remote Scripting), > PHP ASP/VBScript. CPAINT , Ajax JSRS , ,
. JavaScript.
> ,
.
)ojo
\ (Alex Russell), 2004

ttp://dojotoolkit.org
1 Ajax, , [ XMLHttpRequest . JavaScript Web.
)WR (Direct Web Remoting)
(Apache)
r
ww.getahead.ltd.uk/dwr
) Java JavaScript-. SAJAX, JavaScript- Java,
i JavaScript -

. Ajax

631

Web- (, Struts lapestry), KISS/POJO Spring.


OpenSymphony Web Works.
Echo 2

(MPL GPL)
www.nextapp-com/products/echo2
Echo 2 Ajax Java, HTML- JavaScript-, . XML. , JavaScript.
f(m)

http://fm.dept-z.com/

.NET MAScript. , Web-, .


FCKEditor

www.fckeditor.net

WYSIWYG-;
HTML JavaScript-, Web-, CMS,
.. TinyMCE.
Flash JavaScript Integration Kit

www.osflash.org/doku.php?id=flashjs
JavaScript Flash; ActionScript JavaScript- . .
Google AjaxSLT
(BSD)
http://goog-aj a x s l t . s o u r c e f o r g e . n e t
- Google. JavaScript- XSLT XPath. Google Map.

632

V.

3uise

;
mw.javaguise.com

Java (- JSF,
). Ajax.
HTMLHttpRequest
(Angus Tumbull), 2005
(LGPL)
tfww.twinhelix.com/JavaScript/htmlhttprequest/
.
XMLHttpRequest IFrames.
nteractive Website Framework

ittp://sourceforge.net/projects/iwf/
, Ajax. Web- JavaScript, CSS, XML HTML.
XML-, JavaScript-. Web: Ajax .
XMLHttpRequest DOM, .
^ .
Jackbe

*ww.j ackbe.com/solutions/development.html
Ajax; , ASP-,
Java-, .NET- -.
JPSpan
()
uttp://jpspan.sourceforge.net/wiki/doku.php
JPSpan JavaScript . .

. Ajax

633

jsolait
(LGPL)
http://jsolait.net
JavaScript ,
, , , XML-RPC JSON-RPC.
JSON
(
LGPL)
www.j son-rpc.org/
JSON " XML-"; JSON-RPC - , XML-RPC,
JavaScript-. ( Java, Python, Ruby Perl).
JSRS (JavaScript Remote Scripting)
(Brent Ashley), 2000

www.ashleyit.com/rs/jsrs/test.htm
JavaScript- ,
, . : IE 4+, Netscape 4.x, Netscape
6.x, Mozilla, Opera 7 Galeon. : ASP, ColdFusion, PerlCGI, PHP, Python JSP ().
LibXMLHttpRequest
. (Stephen W. Coate), 2003
;
www.whitefrost.com/servlet/connector?file=reference/2003/06/17/libXml
Request.html
"" XMLHttpRequest.
Mochikit
(MIT)
www.mochikit.com/
, , , /, "" DOM. DOM
Array JavaScript
JSON.

634

V.

net W i n d o w s


www.netwindows.org
/ DHTML. , . , Qt (Trolltech) Smalltalk.
.
Oddpost

www.oddpost.com
JavaScript; .
Yahoo!.
OpenRico
(Bill Scott), (Darren James), 2005

http://openrico.org
Ajax.
, ,
, ; .
Sabre Airline Solutions Prototype.
Pragmatic Objects

tittp: / /pragmaticobj e c t s . com/products . html
WebControls JSP, Web-
Java. , "" Web-,
'" Web- HTML-
JavaScript CSS, .
,
.
Prototype
(Sam Stephenson), 2004

ittp://prototype.conio.net/
JavaScript, RIA-. -

Ajax

635

Ajax . JavaScript Ruby on Rails,


Rico Scriptaculous. JavaScript Ruby on Rails,
.
Qooxdoo
(LGPL)
http://qooxdoo.sourceforge.net
Ajax .
. .
RSLite
(Brent Ashley), 2000
www.ashleyit.com/rs/main.htm
,
Remote Scripting (. , JSRS).
Ruby on Rails
(David Heinemeier Hansson), 2004
(MIT)
www.rubyonrails.org
Web- Ajax. Ajax- ,
Ruby on Rails Ajax. ( ) JavaScript-
. . , .
Java-. Ruby on Rails - Ajax.
Prototype Scriptaculous.
Sack
'( MIT/X11)
http://twilightuniverse.com/2 005/05/sack-of-ajax
"" XMLHttpRequest. DOM .
D0M D0M.

636

V.

SAJAX


www.modernmethod.com/saj ax
3AJAX JavaScript- , , . , JavaScript x__calculateBudget ()
Java calculateBudget (),
x_calculateBudget__cb() JavaScript-. JavaScript .
: ASP, ColdFusion, Io, Lua, Perl, PHP, Python Ruby.
Sarissa
(GPL LGPL)
http://sarissa.sf.net
API JavaScript, XML , .
XML, XPath, XSLT JavaScript
XML .
^
Scriptaculous
(Thomas Fuchs), 2004

http://script.aculo.us
,
JavaScript Prototype. ,
.
SWATO
(ASF)
http://swato.dev.java.net
SWATO (Shift Web Application T O . . . ) Java/JavaScript,
Web- Ajax.
Java ,
Servlet 2.3+. JavaScript , XMLHttpRequest. POJO
JSON,
JavaScript- (HTML, XUL, SVG)
JavaScript. (Auto-complete Textbox, Live Form, Live List ..),
Web-.

. Ajax

637

Tibet

www.technicalpursuit.com
API JavaScript.
Web- (SOAP XML-RPC);
Web- (Google, Amazon Jabber).
, JavaScript.
TinyMCE
,

http://tinymce.moxiecode.com/
WYSIWYG-;
HTML JavaScript-, Web-, CMS,
.. FCKEditor.
TrimPath Templates

http://trimpath.com/project/wiki/JavaScriptTemplates
JavaScript .
Walter Zorn's DHTML Libraries

www.walterzorn.com/index.htm
( ), div.
WebORB for .NET
;
www.themidnightcoders.com/weborb/aboutWeborb.htm
Ajax Flash
.NET Web XML.
WebORB for Java
; /
www.themidnightcoders.com/weborb/aboutWeborb.htm
Ajax
Java
XML. Rich Client

Flash
WebSystem

638

V.

(www. themidnightcoders, //index.htm),


( ) API,
Java, Web- XML Enterprise JavaBean. API ;
DataSets DataTables,
JavaScript Recordset.
.

(Mike Foster), 2005



www.cross-browser.com
DHTML,
, , .
XAJAX
. (J. Max Wilson), 2005
/

http://xajax.sf.net
JavaScript .
JavaScript.
x-Desktop
(GPL)
www.x-desktop.org/
"" . , .
, . DOM 2/JavaScript;
; .

(Brad Fults), 2005


http://xkr.us/code/JavaScript/XHConn
"" XMLHttpRequest.

ActionScript, 58
Ajax, 34

, 41

Camino, 65
CGI, 51
Cocoa, 193
CSS, 51; 65; 68; 362

, 374
, 121, 8
Ajax-, 161

D
DOM, 65; 16
DWR, Iffl; 196

, 120
Ajax-, 169

, #35

J
Java Web Start, 59
JavaScript, 6; 65; 66
JSF, 23./
JSON, 215
JSON-RPC,

5-, 291
MySQL, 124
R.
Remote scripting, 34
RMI, 207
Ruby on Rails, 2
s
SA.3AX, ; 196
SOA, 196
SOAP, 278

, 45
, 34; 101
Adapter, .?0P
Fagade, 107; 108
Observer, 111
X M L H t t p R e g u e s t , 65
, 381
, 313
, 152
, 157

, 120
, 304
P
, 101
, 101
, 100

X
XmlDocument, 86
XMLHttpRequest, 86
XSLT, 216

"-",
120
, 42

CSS, 68
, 41
, 305

, 34
-, 188
, 188

, ,

Ajax
..
..
.. , ..
..
""
101509, , . , . 43, . 1
21.04.2006. 70X100/16.
Times. .
. . . 51,6. .-. . 36,86.
2000 . 1385,

" " . , . .
197110, -, ., 15.

K79
681.3.07
""
. ..
.. ..
"'' :
info@williamspiiblishing.com. http://ww\v.wi]Hamspubl is hing.com
115419, , / 783; 03150. , / 152
in, , , , , .
Ajax . : . . - . : "", 2006. 640 . :
. . . .
ISBN 5-8459-1034- (.)
Web-, Ajax.
Ajax: JavaScript, CSS, DOM XMLHttpRequest.
iro, ,
"--" ,
, . Ajax.
, JavaScript .
.
32.973.26-018.2.75
: .
1
, ,
- , Manning Publications Co,
i7.ed translation from the English language edition published by Manning Publications Co. Copyright 2006.
1 rights reserved. No part of this book may he reproduced or transmitted in any form or by any means, electronic or mechaniluding photocopying, recording or by any information storage rcirieval system, without permission from ihe Publisher.
issian language edition published by Williams Publishing House according to the Agreement with R&l Enterprises
lional. Copyright 2006
5-8459-1034-X (.)
1-9323-9461-3 .)

"", 2006
2006. by Manning Publications Co.