[thelist] AJAX: Generlizating Response Handling, RFC

sam at sam-i-am.com sam at sam-i-am.com
Mon May 16 09:40:45 CDT 2005


> I am trying to create a general way to handle the XML responses from
> an AJAX[0] situation. Recall that since it is asynchronous, if there
> are multiple uses of AJAX, there could be multiple and different
> requests dispatched and awaiting responses at any given time. So, it
> is not sufficient to simply have one function that handles the
> responses, and it is not even sufficient to change the response
> handler based on the most recent request (because there could be
> multiple responses incoming, of different types, and that require
> different handling functions).

The way I've done this recently is to use a request id. I have a RemoteRequest
class, and create an instance for each ajax request I need. Each is 
given an id
and registed in a window.remoteRequests object 
(window.remoteRequets[this.id] =
this)
I then have a generic response handler that looks for the id attribute of the
root element, looks up the remoteRequest.
The RemoteRequest object has a couple of things going on. It has a reponse
propertiy, when I can stash the response body when I get it. It has an xhr
property to store the XmlHttpRequest object itself. And it has a 
reponseHandler
property - which is reference to the function (or anonymous function) 
that wants
this response.

In IE, using onreadystatechange you pretty much just get an event that
somethings state has changed, so I have to loop over the 
window.remoteRequests'
xhr properties (objects) to see if any are ready. In gecko/safari 
"this" in the
context of the event handler is the XHR object itself. So its a little quicker
to lookup.

The RemoteRequests are culled when they're handled. AFAIK there's no way to
reuse a XmlHttpRequest object for multiple requests.

There's another way. You can create a unique event handler for each request,
using an anonymous function to pass in your argments to another function, like
so:
  onreadystatechange = new Function("myAjaxResponseHandler('" + requestId +
"')");

Anyhow, its nice to see more people thinking about this - this gave me some
serious brain ache a few weekends ago.

Sam



More information about the thelist mailing list