Matteo Caprari home

Learning Closure. Ajax with*

posted on 12 Nov 2009 Google released closure library, a javascript library good to make rich internet applications. As this is going to be an important library in software developement, I decided to try it. 'Ajax' networking is a good starting point, so I looked into the package and found two promising classes, HxrIo and XhrManager, which I used for my tests. The documentation is clear but sometimes shy about who does what. Fortunately there are plenty of links to the source code, which is well written and documented. The interesting code is below, but there's a more extend version of my closure-library tests. Just hit a url without waiting for a response

// load the modules

// the easy way: static function call with no callback'url/');

// using the send() method of an instance.
new'urlA'); // GET, default
new'urlB', 'POST');

// also works with an Uri object
var uri = new goog.Uri('urlC');
new, 'PUT');

// no http method validation, this is a valid call
new'urlF', 'XXXX');

// send some data with the POST, works as expected
new'urlG', 'POST', 'p1=v1&p2=v2);

// ATTENTION data will not be attached to a GET
// so this call won't do what you may expect.
new'urlH', 'GET', 'p1=v1&p2=v2');

Request data from the server

// an html file as text'sample.html', function(event) {
	var text =;

// an xml file as document object'sample.xml', function(event) {
	var document =;

// a json file as javascript object'sample.json.js', function(event) {
	var data =;

// spot the 404'gone_fishin', function(event) {
	var success =; // false
	var status =; // 404
	var statusText =; // not found

// !!! exceptions in the callback are swallowed, so check your conditions
// (there is interesting error handling stuff in goog.debug.*)'gone_fishin.js', function(event) {
	// I expected some data, but the file is not there
	// and this will raise an exception...
	var data =;
	var field_data = data.field;
	// this statement will not execute...
	// ...BUT you won't see anything in your console.

// a 404 using an XhrIO instance and closure event management;
var io = new;,, function(event) {
	var status =; // 404
Using the connection manager


//, opt_headers, opt_minCount, opt_maxCount, opt_timeoutInterval)
var mgr = new, null, 0, 2);,, function(event) {
	// this is fired once for each send(), even if they are retried
	var xhr = event.xhrIo;

// reusing an id before the request is complete, causes an exception...
try { mgr.send('id_one','/x'); }
catch (e) { /*[] ID in use*/ }

// ...unless the connection is aborted

mgr.send('other_id','/someurl', null, null, null, function(event) {
	// it's ok to reuse an id an after the request completed
	mgr.send('other_id', '/fool');
blog comments powered by Disqus