[jQuery] AJAX module: abort certain requests (as a plugin?)
Hi there,
currently I am missing the possibility to abort certain requests send by
XMLHttpRequest.
I am for example working on a Google Map application in which the
overlay is updated every time a user zooms or moves the map. The data is
retrieved via XMLHttpRequest and triggers an expensive search on the server.
Imagine that if a user wildly clicks the zoom controls then there are
send a lot requests but of these requests only the last one is
interesting, so i want to abort the former ones to save server ressources.
Here is some related information about that problem:
http://www.quirksmode.org/blog/archives/2005/09/xmlhttp_notes_a_1.html
So I started to write an xmlCache inspired by Mark Wubbens EventCache
(http://novemberborn.net/javascript/event-cache):
// enhanced jQuery AJAX module with an request cache to be able to abort
certain requests
$.xmlCache = function(){
var listXml = [];
return {
listXml : listXml,
add : function(xml){
listXml.push(arguments);
},
flush : function(){
var i, item;
for (i = listXml.length - 1; i >= 0; i = i - 1) {
item = listXml[i];
if (item.abort) {
item.abort();
};
item = null;
};
}
};
}();
I had to change the $.xml to this:
$.xml = function( type, url, data, ret ) {
var xml = new XMLHttpRequest();
if ( xml ) {
// abort certain existing request
$.xmlCache.flush();
xml.open(type || "GET", url, true);
if ( data )
xml.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
if ( ret )
xml.onreadystatechange = function() {
if ( xml.readyState == 4 ) ret(xml);
};
xml.send(data)
// add requests to the cache
$.xmlCache.add(xml);
}
};
It would of course be nicer if one could use the request cache as a
standalone plugin, but at the moment I have no idea how to implement
this without touching $.xml... Maybe some of you gurus have an idea
about that? Or what about adding it anyway, John?
I am also thinking about enhancing it so, that not all of your requests
are aborted and that I selectively add them to the cache. This could be
controlled via an optional parameter in the load function, so that it
remains compatible and request caching is by default turned off:
Existing code:
$("#myElem").load(url); // no caching
New code:
$("#myElem").load(url, true); // added to cache
Or maybe it could look like this?
$("#myElem").load(url).addXMLCache(); // added to cache
Does anyone have an idea about a good solution for this?
Happy coding, Klaus
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/