state of ajax
TRANSCRIPT
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 1/82
Musings on the
State of [email protected]
B e n G a l b
r a i t h ’ s
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 2/82
• Founder, Ajaxian.com
• User interface consultant (Ajax / Swing)
• Frequent technical speaker / author
Who is Ben Galbraith?
What is he doing lately?
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 3/82
Does anyone here notknow what Ajax is?
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 4/82
Ajax: A New Approach to Web Applicationsby Jesse James Garrett February 18, 2005
“Google Suggest and Google Maps are
two examples of a new approach to webapplications that we at Adaptive Path havebeen calling Ajax . The name is shorthand for Asynchronous JavaScript + XML , and it
represents a fundamental shift in what’spossible on the Web.”
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 5/82
Ajax: A New Approach to Web Applicationsby Jesse James Garrett February 18, 2005
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 6/82
Would you like to seehow it works?
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 7/82
Ajax == DHTML
• Key Ajax ingredient:
•XMLHttpRequest (a.k.a. XMLHTTP)
• Introduced by MS in 1997
• Copied by Mozilla 1.0 in 2002
• innerHTML helps a great deal
• DOM API snobs notwithstanding
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 8/82
XMLHttpRequest
Method Description
open("method", "URL"[, asyncFlag[, "userName"[,
"password"]]])Setup the request (note the asyncFlag parameter)
send(content) Send the request; “content” is request body (i.e. POST data)
abort() Stop a request in process
getAllResponseHeaders() Return a hash of header/value pairs
getResponseHeader(”header”) Retrieve a response header value
setRequestHeader(”label”, “value”) Set header (overriding browser headers allowed)
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 9/82
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 10/82
Three Main Ajaxian
Architectures
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 11/82
The Ajax Innovators
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 12/82
The Ajax Innovators
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 13/82
The Ajax Innovators
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 14/82
The Ajax Innovators
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 15/82
Ajax is the victory of
the pragmatists over thepurists*
* they want a rematch
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 16/82
Ajax is about more
than sending data back and forth
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 17/82
Ajax has become a
catch-all buzzword forhighly interactive
websites
(get over it)
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 18/82
And the biggestsurprise?
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 19/82
JavaScript doesn’t suck,after all
(but still don’t hire people who call it ‘Java’ on their CV)
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 20/82
What about Flash?Is Flash Ajax?
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 21/82
Web / Ajax Myths
• Ajax is hard
• Cross-browser differences are too painful
• Rich effects (and widgets) are best left todesktop applications
• Off-line mode isn’t possible
• Client-side validation is a pain
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 22/82
Ajax vs. Desktop Apps
Ajax Advantages Desktop Advantages
Ease of development model Much faster than JavaScript
Ease of deployment Advanced graphical capabilities
Mash-ups Tight integration with OS
Separation of concerns Mature UI toolkits
Hackability (e.g., Greasemonkey) Lack of hackability (e.g., security)
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 23/82
Ajax vs. Desktop Apps:
UI “Richness”Web 1.0
Swing/WinForms
Ajax
Flash
Avalon / Cocoa
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 24/82
Premier Ajax Example
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 25/82
Avalon Example
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 26/82
What can Ajax do foryou?
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 27/82
Increase Participation
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 28/82
Richer Interactivity
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 29/82
Portals That Don’t Stink
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 30/82
Forums That Don’t
Stink
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 31/82
Rich, client-side
validation
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 32/82
Ajaxian Frameworks
XMLHttpRequest IFrame ...
Remoting Toolkits(Prototype, Dojo, Mochikit)
UI Toolkits(Dojo, Script.aculo.us, Moo.fx)
Server-side Web Frameworks(ASP.NET + Atlas, JSF + ICEfaces, Tapestry, Rails)
RAD High-level Tools(TIBCO, TIBET)
JavaScriptToolsand
Utilities
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 33/82
Client-side Frameworks(Effects + Remoting)
(Dojo, Prototype + Script.aculo.us, jQuery, Moo.fx + other Moo tools)
Ajaxian Frameworks
XMLHttpRequest IFrame ...
Server-side Web Frameworks(ASP.NET + Atlas, JSF + ICEfaces, Tapestry, Rails)
RAD High-level Tools(TIBCO, TIBET)
JavaScriptToolsand
Utilities
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 34/82
Key Architectural Issues
• Server push
• Cross-domain scripting
•Mash-ups
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 35/82
Server Push
• Problem:
•How to push data from server to client?
• Two solutions:
• Polling (e.g., email)
• Keep-alive
• Some call this “Comet”
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 36/82
Comet
• Coined by the Dojo team (Alex Russell etal.)
• Beware the two connection limit
• Java server implementations:
• DWR
• Jetty
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 37/82
Cross-Domain Scripting
• Problem:
• Page may not request resources outsideof originating domain
• Solution:
• Proxy server
• Browser hacks
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 38/82
Proxy Server
• May be more useful than you would think
• Allows you to:• Track what your users are doing
• Control access to third-party services
(when you care)
• Avoid hackish nature of other solutions
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 39/82
Browser Hacks
• Dozens of ways to do cross-site scripting(XSS); see http://ha.ckers.org/xss.html
• Most popular:
• Dynamic script tag
• IFRAME (built-in to Dojo)
• Flash
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 40/82
TIBCO GI
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 41/82
Ajaxian Frameworks
Prototype Script.aculo.us Dojo
DWR moo tools
jQuery MochiKit GWTRico Yahoo! UI
and a thousand other frameworks...
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 42/82
Ajaxian Framework Survey
0%
11.25%
22.50%
33.75%
45.00%
P r o t o t y p e
S c r i p t . a c u l o . u s
H
a n d - r o l l e d
D o j o
D W R
M o o . f x
j Q u e r y
Y U I
R i c o
A t l a s
M o c h i K i t
G W T
q o o x d o o
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 43/82
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 44/82
Prototype
• Prototype takes the pain out of common Ajax tasks
• Tightly integrated with Ruby-on-Rails
• Can be used with any backend
• Completely undocumented (by its creators)
• Various third-party websites provide varying levels of
documentation
• http://www.sergiopereira.com/articles/ prototype.js.html
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 45/82
Prototype Contents
• Prototype provides three levels of functionality:
• Utility functions (globally scoped)
• Custom objects
• Extended properties on JavaScript native and hosted
objects
• Some folks consider this a no-no
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 46/82
Basic Utilities
• Prototype contains a number of tools that take the painout of DOM manipulation:
• $() function - shortcut for Document.getElementById
• Can take multiple arguments and will return allmatching elements
• $F() function - returns the value of any form control
• Pass it either the element id or the element object
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 47/82
More Basic Utilities
• Try.these() function - takes functions as arguments andreturns the return value of the first function that doesn’tthrow an exception.
var returnValue;
for (var i = 0; i < arguments.length; i++) {var lambda = arguments[i];try {returnValue = lambda();
break;} catch (e) {}}
return returnValue;
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 48/82
Ajax Helpers
• The Ajax object provides a number of helpful Ajax-
related functionality
• At its simplest, can be used to obtain XHR in a cross-browser way:
var xhr = Ajax.getTransport()
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 49/82
Ajax Helpers
• Implementation of Ajax.getTransport():
var Ajax = {
getTransport: function() {return Try.these(
function() {return new ActiveXObject('Msxml2.XMLHTTP')
},function() {
return new ActiveXObject('Microsoft.XMLHTTP')},
function() {return new XMLHttpRequest()}) || false;
}}
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 50/82
Ajax Helpers
• Provides higher-level functionality for performing Ajaxoperations:
• Ajax.Request() object - takes a url and an “options”object as arguments
• Performs an XHR request
• Options argument specifies XHR configurationparameters and one or more callbacks
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 51/82
Ajax Helpers
• Options object:
• Created using anonymous object creation syntax:{ method: ‘get’, onComplete: callBackRef }
• Supported properties:
• method, asynchronous (true/false), parameters,postBody, requestHeaders (hash), onLoading,onLoaded, onInteractive, onComplete
Aj R t
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 52/82
Ajax.Request
Examplevar request = new Ajax.Request(
‘/someUrl’,
{ method: get, onComplete; myCallBack }
);
function myCallBack(xhr) {
$(‘someElementId’).innerHTML = xhr.responseText;
}
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 53/82
Ajax Helpers
• Ajax.Updater() object - takes an element id, a url and an“options” object as arguments
• Executes XHR and displays response as contents(innerHTML) of specified element
• First argument can be an anonymous object with asuccess property and a failure property set to the ids
of elements
• Executes JavaScripts contained in response HTML
Aj U d t
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 54/82
Ajax.Updater
Example
var request = new Ajax.Updater(
‘someElementId’,
‘/someUrl’,
{ method: ‘get’,
parameters: ‘value=foo’ }
);
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 55/82
Ajax Helpers
• Ajax.PeriodicalUpdater() object - takes an element id, aurl and an “options” object as arguments
• Same behavior as Ajax.Updater() but continuouslyperforms request every 2 seconds
• frequency property on options object controls theupdate frequency in seconds
• stop() function halts the updating; start() functioncan restart it
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 56/82
JavaScript Extensions
• Number.toColorPart() function - converts decimal to hex
• String.stripTags() function - removes any tags from thestring
• String.escapeHTML(), String.unescapeHTML()
• Document.getElementsByClassName()
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 57/82
Custom Objects
• Element object makes manipulating elements mucheasier:
• Element.show(), Element.hide(), Element.toggle() -take an unlimited number of element id or references
• Show/hide based on CSS display attribute
• Element.remove() - nukes element by id or referencefrom the DOM
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 58/82
Custom Objects
• Element.addClassName(), Element.hasClassName(),Element.removeClassName() - take two arguments:element id (or reference) and the class name
• Field.clear() - takes an unlimited number of formelement ids or references and clears their values
• Field.present() - takes form elements ids or references;
returns true if all are non-blank
• Field.focus(), Field.select(), Field.activate() - takes anelement id/ref, and focuses, selects, or focuses/selects
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 59/82
Custom Objects
• Form.serialize() - takes form element id/ref; returns theHTTP query string
• Form.getElements() - takes form element id/ref; returnsarray with all form elements
• Form.disable(), Form.enable(),
Form.focusFirstElement(), Form.reset() - take formelement id/ref
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 60/82
Prototype and Ruby
• Prototype implements methods and ideas familiar to a
Ruby programmer
• Collection inspection and manipulation methodsembedded directly on the collection object itself
• Closure-centric syntax
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 61/82
each
• var Numbers = [0, 1, 4, 5, 98, 32, 12, 9];
• Traditional Iteration:
for (var i = 0; i < Numbers.length; i++) {
alert(Numbers[i]);
}
• New “each” style:
Numbers.each(function(num) {
alert(num);
});
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 62/82
collect
var Products = [{name: 'Basecamp', company: '37signals', type: 'Project Management'},
{name: 'Shopify', company: 'JadedPixel', type: 'E-Commerce'},{name: 'Mint', company: 'Shaun Inman', type: 'Statistics'}
];
• collect: iterate over an Array and return the results as anew array:
return Products.collect(function(product) {
return product.company;}).join(', ');
• Result: “37signals, JadedPixel, Shaun Inman”
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 63/82
include
var Artists = ['Air', 'Björk', 'Arturo Sandoval', 'Orb'];
• include: check if a value is included in an array (returnsboolean)
return Artists.include(‘Depeche Mode’);
• Result: false
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 64/82
And Much More...
• Prototype also contains utilities for inserting values intoexisting HTML content, event handling, JavaScript objectdefinition, HTML element positioning, and more
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 65/82
DWR
• DWR (Direct Web Remoting) provides tight integrationwith Java
• DWR provides two major functions:
• A dynamic Java→ JavaScript proxy generation library(engine.js)
• Utility library of miscellaneous JavaScriptfunctionality (util.js)
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 66/82
Using DWR
• Step 1: Add the DWR servlet to your project
• Step 2: Create a DWR configuration file
• Step 3: Add DWR JavaScript to your HTML
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 67/82
The DWR Servlet
• Step 1: Configure the DWR servlet
<servlet>
<servlet-name>dwr-invoker</servlet-name><servlet-class>
uk.ltd.getahead.dwr.DWRServlet</servlet-class><init-param>
<param-name>debug</param-name><param-value>true</param-value>
</init-param></servlet>
<servlet-mapping><servlet-name>dwr-invoker</servlet-name><url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 68/82
The DWR Servlet
• The DWR servlet provides some fairly neat interactive
capabilities
• http://[host]:[context]/dwr/
• Consider turning off debugging before deploying to
production
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 69/82
Configuring DWR
• Step 2: Configure DWR
• DWR does not allow arbitrary execution of any Javacode unless you explicitly expose the Java code
• Exposure of Java classes occurs in a DWR-specific
configuration file: dwr.xml
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 70/82
Simple dwr.xml
<!DOCTYPE dwr PUBLIC"-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"
"http://www.getahead.ltd.uk/dwr/dwr10.dtd"><dwr>
<allow><create creator="new" javascript="Validator">
<param name="class"value="org.galbraiths.Validator"/>
</create></allow>
</dwr>
Specify the class to expose
Specify an arbitrary name for the JavaScript proxy
Specify how tocreate the object
(i.e., Spring vs “new”)
* classes not instantiated when a method is static
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 71/82
JavaScript
• Step 3: Add DWR JavaScript
•DWR servlet acts as a mini-server for delivering JavaScript to the browser
• Dynamically generates JavaScript proxy objects atrun-time
• You must explicitly reference a JavaScript file for eachproxy you wish to use
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 72/82
JavaScript Example
<script type="text/javascript" src="/dwr/engine.js"></script><script type="text/javascript" src="/dwr/Validator.js"></script>
<script type=”text/javascript”> Validator.echoMethod(‘Hello, world!’, callback);
function callback(data) {alert(data);
}</script>
Core DWR JavaScript:required for proxy stuff
Proxy JavaScript:required to access an instanceof the Java “Validator” type
DWR creates JavaScript methodsthat proxy the Java methods
public String echoMethod(String arg) {return arg;
}
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 73/82
DWR Configuration
• You can restrict the set of methods exposed on an object
• Use either an include or exclude model, but not both
• Can integrate with JAAS to require a role for methodinvocation
• You can set the scope of the beans DWR instantiates
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 74/82
DWR Configuration
• By default, DWR blocks remoting of arbitrary JavaBeans
• But, you can enable it easily enough (see next slide)
• Remember, JavaScript does not support methodoverloading
• Most recent definition wins (is the order guaranteed?not likely)
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 75/82
Example
<dwr><allow>
<create creator="new" javascript="Ledger" scope="request"><param name="class" value="org.galbraiths.Ledger"/>
<exclude method="revealSensitiveFinancialInfo"/>
<auth method="cheatEmployeesOutOfMoney" role="boss"/></create>
<create creator="new" javascript="Validator"><param name="class" value="org.galbraiths.Validator"/>
<include method="validateCustomerId"/> <include method="validateTicketNumber"/>
</create>
<convert converter="bean" match="org.galbraiths.SomeBean"/></allow>
</dwr>
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 76/82
• DWR allows you to define new ways to create beans andcustom converters for JavaBeans
• "creators" and "converters" must be registered in an<init> element in the configuration file:
<init><creator id="..." class="..."/><converter id="..." class="..."/>
</init>
Extensibility
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 77/82
Additional Features
• DWR makes it easy to display a "Loading..." indicator
• Exposes a pre- and post- hook after some remoteoperation takes place:
• DWREngine.setPreHook(function)
• DWREngine.setPostHook(function)
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 78/82
Additional Features
• Worried about latency? DWR allows you to batchopereations:
• DWREngine.beginBatch()
• DWREngine.endBatch()
• Race conditions caused by asynchronicity got youdown?
• DWREngine.setOrdered(true) forces serial FIFOexecution of DWR requests
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 79/82
Script.aculo.us
• Requires Prototype
• Reduces many effects to one line of JavaScript:
<div onclick="new Effect.Fade(this)">
...
</div>
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 80/82
The Effects
• Each effect takes either a DOM node or the element id(or multiple element ids)
• Effect.*:
• Appear, Fade, Puff, BlindDown, BlindUp, SwitchOff,SlideDown, SlideUp, DropOut, Shake, Pulsate,Squish, Fold, Grow, Shrink, Highlight
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 81/82
Debugging Tips
• Use the DOM Inspector to observe the current state of your page
• Use MODI for easier live inspection and DOM
manipulation
• Use the JavaScript console to check for errors
• Use MochiKit logging and interpreter
• Use Venkman or Microsoft Script Debugger to troubleshootbehaviorial problems
• Or, just use Firebug
8/4/2019 State of Ajax
http://slidepdf.com/reader/full/state-of-ajax 82/82
Futures?
• SVG
• Canvas
• JIT
•Off-line
• Flash