AJAX - The Complete Reference

(avery) #1

526 Part III: Advanced Topics


To see real-time communication in your Web browser via Flash, see the example at
http://ajaxref.com/ch10/flashsocket.html. It works quite nicely; the only thing you might
not like is that the browser status might show a strange communications message:

Server Event Listeners

The WhatWG specification (www.whatwg.org) defines server events to help enable push-
style applications. While the specification is still quite new, Opera 9 already contains partial
support for this interesting idea, and other browsers are likely to follow. The basic idea is
that we include a new tag:

<event-source />

and set the src attribute to a server-side program of interest:

<event-source src="servertime.php" id="timeEvent" />

We then use JavaScript to bind an event listener to the tag:

document.getElementById("timeEvent").addEventListener("update_time",
handleResponse, false);

listening for events of particular types and then specifying the callback to handle them.
A complete example that sets up the client side is shown here. Note that we don’t bother
with direct insertion of the new tag; we just use the DOM to insert it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.
w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 10 - Opera Server Events</title>
<script src="http://ajaxref.com/ch10/ajaxtcr.js" type="text/javascript"></script>
<script type="text/javascript">
function sendRequest()
{
var timeEvent = document.createElement("event-source");
timeEvent.id = "timeEvent";
timeEvent.setAttribute("src", "opera.php");
timeEvent.addEventListener("update_time", handleResponse, false);
document.body.appendChild(timeEvent);
}
function handleResponse(event)
{
$id("hellodiv").innerHTML = event.data;
}
AjaxTCR.util.event.addWindowLoadEvent(sendRequest);
</script>
Free download pdf