Sei sulla pagina 1di 19

AJAX

Asynchronous Java and XML (XMLHttpRequest, actually)

AJAX
AJAX: Asynchronous Java and XML


AJAX is sometimes called Web 2.0

AJAX is not a technology per se, but a web development method


 

The aim is to increase the interactivity of a website When you work with a web page, the web page itself can be interacting with the server, but without reloading the (whole) page you are on The result is an uninterrupted user experience, with full server-side capabilities

How Does AJAX Work?


AJAX is merely putting to use 2 existing technologies: JavaScript and XML
 

JavaScript handles all the client-side functionality, such as capturing events XMLHttpRequest is used to submit an HTTP request to the server to exchange data
This occurs within the JavaScript of the page XMLHttpRequest was developed for Internet Explorer, and adopted by all other browsers

The page is not reloaded, but the JavaScript can use this method to send/receive data to/from the server

How Does AJAX Work?


Clients Browser Web Server HTML Page Database or Other Data

Event handlers, etc.

JDBC, etc.

JavaScript Module

HTTP

JSP Page

XMLHttpRequest
XMLHttpRequest can load HTTP requests:


Synchronously: The browser will wait for the response


This is a simpler model for the developer, but the resulting blocking is not acceptable

Asynchronously: The browser will not wait, but the object will call an event handler when the loading status changes
This is what you would use in practice

XMLHttpRequest Methods
abort()

Stops the current request


getAllResponseHeaders()

Returns all headers (name and value) as a string


getResponseHeader(<headerName>)

Returns the value of the specified header


open(GET/POST, URL [, true/false[, <username>,<password>]])

Opens a connection and retrieves response from the specified URL. Can also specify optional values method (GET/POST), username and password for secured sites
send(content)

Transmits request (can include postable string or DOM object data)


setRequestHeader(<name>, <value>)

Assigns values to the specifed header

XMLHttpRequest Properties
onreadystatechange

Event handler for an event that fires at every state change


readyState

0 = uninitialized 1 = loading 2 = loaded 3 = interactive 4 = complete


responseText

Data returned from server in string form


responseXML

DOM-compatible document object of data returned


status

HTTP status code (i.e., 200, 404, 500, etc.)


statusText

String message associated with the status code

AJAX: Examples
This is a very simple idea, but it can have very nice results, such as:


Google Maps (and A9 Maps):


An image displaying a map of a specified region is inserted into a web page The user clicks the scroll left button The JavaScript module loads a new image and inserts it into the current document

Google Suggest (and Amazon Suggest):


The user types in part of a keyword The JavaScript module sends the partial keyword to the server, and gets back a list of matches, which are shown to the user

AJAX: Practical
Ok, so lets create a real example Remember in HaggleCity, when selling an item, and we had to choose category and subcategory?


I put in JavaScript that posted the page back to the server, which generated the same form, except with the correct subcategories for the currently selected category The result was that the form reloaded every time I selected a category from the list

One obvious solution is to write the subcategory population code completely in JavaScript


However, if the subcategories change, I have to manually edit the code (which is not acceptable)

HaggleCity::sellItem: Old Version


Here is the old code:
<script language=javascript type=text/javascript> function updateSubcategories() { // submit the form (to POST back to the server) return document.forms[1].submit(); } </script> <select name="category" onChange=return updateSubcategories();"> populate category list </select>

HaggleCity::sellItem: With AJAX


<script language=javascript type=text/javascript> var httpRequest; if (window.XMLHttpRequest) { // This is for Mozilla/Firefox/Netscape/Opera/Safari httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // This is for Internet Explorer httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } function updateSubcategories() { var selectedCategory = getCategory(); var loadStatus = document.getElementById("loadStatus") loadStatus.innerHTML = "<img src='pleasewait.gif' /> Loading... Please Wait."; // submit the form (to POST back to the server) // return document.forms[0].submit(); // disabled in favour of AJAX method below // Use XMLHttpRequest to get the data from the server httpObject.open("GET", "getSubcategories.jsp?delay=${param.delay}&category="+escape(selectedCategory), true); httpObject.onreadystatechange = handleResponse; httpObject.send(null); } ... </script>

HaggleCity::sellItem: With AJAX


Part 2:
function handleResponse() { // 4 indicates loading is complete if ((httpObject.readyState == 4) && (httpObject.status == 200)) { // remove the "Loading... Please Wait" message document.getElementById("loadStatus").innerHTML = ""; // replace the subcategory list with the output var subcat = document.getElementById("subcategoryPanel") subcat.innerHTML = httpObject.responseText; } }

HaggleCity AJAX: Advantages


Note that the form seems to work more quickly when categories are selected What has changed?
 

The data sent from the server was significantly reduced


Only the select tag is sent to the client each time

The remainder of the form does not change


In fact, the user can continue to use it while waiting for the response

What hasnt changed?




The selection of a list item still results in an HTTP request, and suffers the latency thereof
This latency necessitates the Please Wait message, to prevent the user from clicking the buttons/links or selecting from the lists a second time

A Second Example
Lets make another AJAX-enabled web page The form provides a TV show listing
  

When a TV show is clicked, the details of that show are displayed However, the page is not reloaded The TV show details are loaded using XMLHttpRequest, and inserted into an empty <div> tag when received

A Third Example
An AJAX-enabled Tic Tac Toe game is developed


playGame.jsp initializes the game


Basically, a two-dimensional ArrayList is created, storing , X, or O

viewBoard.jsp displays the current board


All other pages import this page All empty positions are filled with a link to enterPlayerMove.jsp, if its the players turn

 

enterPlayerMove.jsp
This page adds a move for X to the player at (x,y)

enterComputerMove.jsp
This page adds a move for O at a random open position

AJAX-Enabled Websites
Kiko (Calendar) - www.kiko.com Writely (Word Processor) www.writely.com A9 (Search Engine) www.a9.com A9 Maps (Maps) maps.a9.com Google Maps (Maps) maps.google.com Google Suggest (Search Helper) www.google.com Google Mail (E-Mail) gmail.google.com Meebo (Instant Messaging) www15.meebo.com Kayak (Flights Search) www.kayak.com

AJAX Libraries
Ajax Tags: JSP tags Apache Ajax: JSP tags Java Web Parts: JSP tags Atlas: API for .NET Ajax.NET: API for .NET Direct Web Remoting: Java Javascript & Javascript Java DoJo: JavaScript lib Backbase: Complete Framework, GUI + integration with popular architectures (e.g. J2EE)

AJAX Tags
The tags created for AJAX tags are basically a ready made taglib for AJAX apps:


  

autocomplete: A field is filled in with matching words (in a list generated on the server side), similar to Google Suggest callout: A popup (e.g. for definitions) updateField: One form field is updated when data is supplied to another form field select: A listbox is populated based on the value of another listbox (i.e. like the sellItem.jsp page)

AJAX Tags
The tags created for AJAX tags are basically a ready made taglib for AJAX apps:
 

pagearea: An area that can be updated separately


Similar to the target attribute in an anchor

portlet: A window-like region


Can be refreshed, minimized/maximized, closed independently of the rest of the page Can also be set to automatically refresh (e.g. stock ticker)

 

tabpanel/tab: A tabbed-pane control toggle: An image-based toggler (like a checkbox)

Potrebbero piacerti anche