AJAX
Lecture Notes for CS349W
Fall Quarter 2008
John Ousterhout
- "Asynchronous Javascript And XML"
- Very simple idea: interact with server without changing the page
that is displayed.
- Opens up a large number of dynamic behaviors.
- Basic idea:
- From Javascript, can issue an HTTP request:
- URL including query values
- Protocol (GET/POST)
- Message body (for POST)
- Javascript function to invoke when the request completes
- This call returns immediately (the request continues asynchronously
in background).
- Eventually a response arrives from the server: at this point the
function specified by the invoker is called; it has access to the
response, including both headers and body.
- For details, see
W3C Documentation for XMLHttpRequest
- Key value of AJAX: can update part of a page without redisplaying
the entire page:
- Refresh portions of a page that are changing dynamically.
- Incrementally download data as it is needed
- Fetch tree nodes when parent is expanded.
- Update choices in a menu when some other selection changes
(example: pick a major city in a state).
- Fetch more map data around the edges as the user drags the map.
- Make incremental updates (e.g., notify server that a table row has
been moved or a photo has been tagged).
- Originally, it was assumed that the response would be an XML document
containing one or more values (e.g., contents for new rows to add
to a table). DOM provides facilities for parsing the XML and
retrieving values.
- Common practice seems to be moving away from this pattern:
- Often, it's easier to just send a Javascript program, which then
gets eval-ed in the browser; can be simpler than trying to parse XML.
- Libraries provide higher-level patterns that make the underlying
details irrelevant.
Summary of browser facilities
- Document model:
- HTML for initial specification
- DOM for dynamic updates
- Pretty good support for text and images
- Stylesheets provide flexible control over formatting
- User input:
- Good support for basic forms
- Can extend with Javascript
- Event model sufficient
- Dynamic behavior:
- Javascript a fine language for programming (small things) in the
browser.
- AJAX permits dynamic and granular updates.
- Weaknesses:
- No pixel-level access:
- Can't draw lines, circles, etc.
- Can't modify images on-the-fly.
- Limited control over layout:
- Basic document flow
- Tables
- Absolute positioning
- Hard to build general-purpose geometry managers: can't get
"desired size" of elements, only actual size.
- The main source of data is in a different application, potentially
far away.