Thursday, June 30th, 2005

Pushlets and XHR

Category: Library

The Pushlets team has added Ajax to their HTTP-based publish/subscribe framework.

You can check out an example here.

In the code they have functions for the various events:

function leave() {
doRequest(‘/pushlet/pushlet.srv?p_event=leave&p_id=’ + sessionID );
}

and then the typical XHR to access the pushlet server side:

function doRequest(url) {
// Create XMLHttpRequest object and open URL in async mode
xmlhttp = new XMLHttpRequest();
xmlhttp.open(“GET”, url, true);

// Response handler
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
onResponse(xmlhttp.responseText);
}
}
// No need to send body
xmlhttp.send(null);
}

and the meat in onResponse:

function onResponse(responseText) {
// Response is XML document: parse it using XParse
// Using XML DOM is too much hassle…
var xmlDoc = Xparse(responseText);

// XML document is parsed into tree of arrays, contents[0] is element
eventElements = xmlDoc.contents[0].contents;

// Go through all elements
for (i=0; i< eventElements.length; i++) { nextEvent = eventElements[i]; // Determine action based on event type eventType = nextEvent.attributes['p_event']; if (eventType == 'refresh') { // Pull mode: need to sleep and refresh refreshURL = nextEvent.attributes['p_url']; timeout = nextEvent.attributes['p_wait']; setTimeout("refresh()", timeout); } else if (eventType == 'join-listen-ack') { sessionID = nextEvent.attributes['p_id']; } else if (eventType == 'leave-ack') { sessionID = null; eventCount = 0; } } }

Posted by Dion Almaer at 2:49 pm
Comment here

+++--
3.7 rating from 13 votes

Comments Here »

Comments feed

Leave a comment

You must be logged in to post a comment.