Upload
rahmedsct
View
1.591
Download
0
Tags:
Embed Size (px)
Citation preview
© Rizwan Ahmed 2008
AJAX: The New Paradigm for Enterprise
Web Applications
Rizwan Ahmed
2
What is AJAX?
New approach to web interaction Involves transmitting only small amounts of
information to and from server Gives user the most responsive experience Traditional web app model – browser initiates
requests and processes HTML response AJAX model provides an intermediate layer –
AJAX Engine to handle this communication
3
Components of AJAX
Asynchronous data retrieval using XMLHttpRequest
Data interchange and manipulation using XML, XPath and XSLT
Dynamic display and interaction using the Document Object Model
Standards based presentation using XHTML and CSS
JavaScript binding everything together
4
Characteristics of AJAX apps
Continuous Feel Real-Time updates Established Standards Non proprietary Language Neutrality XML declarative interface Non Browser specific
5
AJAX Model
6
Sequences of AJAX vs. Traditional web model
7
Who is using AJAX?
Yahoo! Web Search
8
Who is using AJAX?
Google Maps
9
Who is using AJAX?
Yahoo! News
10
Beneath the Hood
At the very core of any AJAX app:
Request variable in JavaScript instantiated with one of the following methods:
ActiveXObject(“Microsoft.XMLHTTP”) for IE 6 browsers
XMLHttpRequest Object for all others IE 7+ will have native XMLHttpRequest
support
11
XMLHttpRequest
A JavaScript class built into the browser that lets you make Asynchronous HTTP requests
Class is instantiated by custom JavaScript code triggered from HTML events
A Forward URL string representing the server resource is included with each call
A Call Back JavaScript function is invoked depending on the state of the HTTP Response
12
XMLHttpRequest Properties
onreadystatechange – informs Ajax engine that response is ready for call back function
readyState – current state of the HTTP call responseText – the text result of the request responseXML – DOM XML object result of the
request status – HTTP status code of the response statusText – HTTP status text
13
XMLHttpRequest Example
var key = document.getElementById("key");
var url = "/server/resource?key="+key.value;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
req.open("Get",url,true);
req.onreadystatechange = callback;
req.send();
14
Server Resource
public class ServerResourceServlet extends HttpServlet { public void doGet(req, res) { String key = req.getParameter("key"); ……. if (key != null) { returnXML = new StringBuffer("\r\n<returnedData>"); returnXML.append(…); returnXML.append("\r\n</returnedData>"); // setup the response res.setContentType("text/xml"); // write out the xml string res.getWriter().write(returnXML.toString()); } }}
15
Callback
Callback can be either discrete functions or anonymously declared.
function callback(){ if (req.readyState==4){ if (req.status == 200){ modifyHTML(…); } } clear(); }
16
Mining the Response
function modifyHTML(){ var resp = req.responseText; var parser = new DOMParser(); var dom = parser.parseFromString(resp);
var val = dom.getElementsByTagName(..); var elemId = document.getElementbyId(..); elemId.value = val[0].childNodes[0].nodeValue;……….}
17
Cross Browser Compatibility
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject(Msxml2.XMLHTTP);
} catch (Exception e) {
req = new ActiveXObject(Microsoft.XMLHTTP); }
}
18
Data Vehicles
● XML
<returnedData> <zip>29203</zip> <city>Columbia</city> <state>SC</state></returnedData>
● Plain Text (Custom formatted eg. CSV, HTML) returnedData;29203;Columbia;SC
19
Data Vehicles (cont.)
● JavaScript Object Notation (JSON)
A lightweight data format based off the JavaScript syntax. Definitions can be included and parsed with JavaScript.
{“returnedData”:{ “zip”: “29203”, “city”: “Columbia”, “state”: “SC”}}
20
Some AJAX Libraries
● DoJo Toolkit (http://dojotoolkit.org/)
● Rico Toolkit (http://openrico.org/)
● DWR Toolkit (http://getahead.org/dwr/)
● Prototype (http://prototypejs.org)
● AjaxTags (http://ajaxtags.sourceforge.net)
21
AJAX Libraries (cont.)
DoJo Toolkit
● DoJo is an open source DHTML toolkit written in JavaScript and include the AJAX specific libraries dojo.io; dojo.rpc; dojo.json
var key = document.getElementById("key"); dojo.io.bind({ url: "/server/resource?key="+key.value, load: function(type, data, evt) { callback(data); }, error: function(type, data, evt) { reportError(data); }, mimetype: “text/plain” });
22
AJAX Libraries (cont.)
Rico ToolkitRico is an open source toolkit allows for registering AJAX request handlers and HTML elements as AJAX response objects● ajaxEngine.registerElement(‘rHdl’,’server url’) ajaxEngine.sendRequest(‘rHdl’,’key=‘+key.value)
● Server resource must respond with XML formatted document. Rico matches id attributes in the document with fields in the HTML form and populates it accordingly
● No callback functions are necessary
23
AJAX Libraries (cont.)
DWR ToolkitDirect Web Remoting is an open source AJAX framework for Java/JSP● DWRServlet on the server end runs the whole show. Instantiated during application load time
● On browser side a JavaScript wrapper library is created using Java’s Reflections API that mirror the server side classes
● An XML configuration file dwr.xml provides the plumbing that connects the server side classes with the JavaScript
24
AJAX Libraries (cont.)
Prototype Framework● Prototype is another open source framework that does AJAX requests with browser differences abstracted from user
parameterString = “key=" + escape(key); new Ajax.Request(“/server/resource", { method: "get", parameters: parameterString, onSuccess: function(request) { var result = request.responseText; ….. }, onFailure: function(request) {…...} });
25
AJAX Libraries (cont.)
Prototype Framework (cont.)● Prototype includes enhanced library support for JSON, DOM and other utilities
● Prototype is largely used in conjunction with scriptaculous
● Scriptaculous toolkit provides easy to use, cross browser JS libraries. Includes animation framework, visual effects, drag and drop features and AJAX controls
26
AJAX Libraries (cont.)
AJAX using Custom Tags● Writing Ajaxian code over and over can be tedious and error prone
● Encapsulate the functionality into a custom JSP tag for easy reuse
● Using Tag Libraries will save time and enhance reusability and maintainability of the code
● Consists of a TLD and Tag Support class
● There are a number of 3rd party Tags that encapsulate Ajaxian functionality
27
AJAX Libraries (cont.)
AjaxTags
● AjaxTags is a Sourceforge project. Allows use of AJAX with minimal effort● Consists of the following representative tags:
Autocomplete – Displays list of entries that match text into the autocomplete field HTML Content Replace - Connects a content area to an HTML onclick event Portlet – Adds a portlet to a JSP page Select/Dropdown – Populates a select field based on selection in another select field
28
AJAX Design Patterns
A. Predictive Fetch
Traditional web solutions – app has no idea what is to come next
Fetch on Demand – User through his actions requests data retrieval
Unfortunate side effect of forcing the start-and-stop model of user interaction upon the user
29
AJAX Design Patterns
A. Predictive Fetch (cont.)
Guess what the user is going to do next and pre-fetch the appropriate data
Simple use cases where predicting user actions are easier
Anticipate and preload information to make app feel lighter and responsive
Must exercise “logical to assume” criterion
30
AJAX Design Patterns (cont.)
B. Submission Throttling
In AJAXian apps user interacts with the app by sending async requests
The timing and frequency of sending requests is of paramount importance
One solution would be to send data to server each time a user action occurs
This generates a large number of requests in a short period of time
31
AJAX Design Patterns (cont.)
B. Submission Throttling (cont.)
Using ST you buffer the data on the client and then send it at pre-determined intervals
Yahoo! and Google search does this
Wait for a certain amt of time and then sends all data in the text box
The delay from typing to sending has been fine tuned
32
AJAX Design Patterns (cont.)
B. Submission Throttling (cont.)
ST begins when application first loads or a specific user action
Client side function is called to begin the buffering of data
Determination when, what and how much to send depends on use case
May want to send data when it reaches a particular size
33
AJAX Design Patterns (cont.)
C. Periodic Refresh
Process of checking for new server info at specific intervals – polling
In its simplest form a loop can be established to run indefinitely setInterval(callServer, REFRESH_PERIOD_MILLIS);
Periodic Refresh fakes a back channel situation forcing server data back to client
34
AJAX Design Patterns (cont.)
C. Periodic Refresh (cont.)
Successfully used by ESPN to update its online scoreboards:
(sports.espn.go.com/nfl/scoreboard)
35
AJAX Design Patterns (cont.)
C. Periodic Refresh (cont.)
The period between refreshes would ideally be 0. Latency issues.
Entails significant resource cost. Ensure bandwidth and associated infrastructure.
Key design aim must be to increase the average refresh period and reduce content per refresh
36
AJAX Design Patterns (cont.)
D. Multi-Stage Download
Lasting problems on the web - the speed at which pages download
Residential broadband has caused many sites to increase multimedia content (animation, pictures etc.)
Slower download times as everything is loaded in random order
37
AJAX Design Patterns (cont.)
D. Multi-Stage Download (cont.)
AJAX pattern where only the basic functionality is loaded initially
The page then begins to download other components that should appear
Popularized by start.com
User driven activity determines content loading behind scenes
38
AJAX Design Patterns (cont.)
D. Multi-Stage Download (cont.)
Page must work in its simplest form for non-AJAX browsers
Provide “graceful degradation” – those supporting AJAX technologies will get extensive interface while others get the bare bones
Important if you expect search engines to crawl through your web site
39
Request Management
● Issues related to the frequency and timing of requests
● Major concern is the number of times that communication occurs between client and server
Server can get bogged down while trying to handle multiple user requests
Client can become unresponsive while waiting for server responses
40
Request Management
● Most browsers have inbuilt queuing mechanisms which is not robust
● Works well when requests are few and far in between
● In real world requests are being sent from various parts of the application at different times
● No control over when requests are sent or what order they should be sent
41
Request Management (cont.)
● Implement a Priority Queue
Priority based promotion. Values inserted based on request priority.
Age based promotion. Requests bumped up the priority based on age.
RequestManager Object to handle XMLHttpRequest
42
Recap
What is AJAX Asynchronous data retrieval using XMLHttp Data interchange and manipulation using XML/XPath/XSLT Dynamic display and interaction using DOM Standards based presentation using XHTML and CSS JavaScript binding everything together
Characteristics of AJAX applications Continuous feel/Real Time Updates Established Standards/Language neutrality Dynamic display and interaction using DOM
AJAX Libraries AJAX Design Patterns
Predictive Fetch Submission Throttling Periodic Refresh Multi-Page Download
43
References
http://ajaxpatterns.org
http://www.w3cschools.com/ajax
http://www.adaptivepath.com/ideas/essays/archives/000385.php - Seminal Article on AJAX
Ajax on Java: Steven Douglas Olson
Professional AJAX: Zakas, McPeak, Fawcett