coder and technology lover
goog.net.XhrIo: make simple ajax calls with Google Closure
Closure has a consistent package called goog.net, which contains a lot of classes to work with ajax and remote http requests. In this post I want to show how to create a basic xhr object to make get/post calls, listen for related ajax events and send data to server. Once imported the main js file (base.js), we will require the following:
1 2 3 4 | goog.require("goog.dom"); goog.require("goog.net.XhrIo"); goog.require("goog.structs.Map"); goog.require("goog.Uri.QueryData"); |
The most important import is goog.net.XhrIo, which represents the object wrapping the XmlHttpRequest and allows us to retrieve and send information to/from the server. This class is a pretty low level api, which means that several tasks are not as simple and automatic as they would in jQuery or such libraries, but on the other hand this offers us more control and consciousness of what we are going to do.
The first step is instantiate an object of type goog.net.XhrIo and take a reference to it:
1 | var request = new goog.net.XhrIo(); |
Then we will be able to listen for events:
1 | goog.events.listen(request, "complete", ajaxCallBack); |
In this case we will listen to a “complete” event, which is an event always dispatched by goog.net.XhrIo even if the call fails. We can however listen to a “success”, an “error”, an “abort” or a “readystatechange” event, but in most cases listen only to “complete” is the best and easy choice. If we decide to listen to “complete” event, we will handle the result and ask to goog.net.XhrIo if the ajax call has been successful or not:
1 2 3 4 5 6 7 8 9 10 11 12 13 | goog.events.listen(request, "complete", function(){ if (request.isSuccess()) { // do something cool } else { // display an apologize message } }); |
To start the request we will use the send() method, which accepts the following parameters: the url to call (the only mandatory argument), the method to use (usually “GET” or “POST”), a query string containing the parameters to send and a map (key-value object) representing custom headers to send.
Before starting the ajax call, let’s see how to create an object that will holds data to send to the server by using the class goog.Uri.QueryData:
1 2 3 4 5 | var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({ title: "Test ajax data", content: "foo", param1: 2500 })); |
As I can see from Closure reference, the approach above is the faster way to create a “data container” in order to send data with ajax. We can use the static method createFromMap() of goog.Uri.QueryData and pass an anonymous map (which has no reference) to it. A map is one of the several objects coming from the Java world that has been introduced in Closure by Google under the package goog.structs, it is essentially an object containing a certain number of keys holding a determinate value. Once we have our data stored into a goog.Uri.QueryData we will use the toString() method to send it through ajax, send() method in fact expects a string representation of the data (param1=value¶m2=value…) not an object:
1 | request.send("ajax-test.jsp", "POST", data.toString()); |
The complete example’s code is the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | goog.require("goog.dom"); goog.require("goog.net.XhrIo"); goog.require("goog.structs.Map"); goog.require("goog.Uri.QueryData"); function doRequest() { // create the xhr object var request = new goog.net.XhrIo(); // create a QueryData object by initializing it with a simple Map var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({ title: "Test ajax data", content: "foo", param1: 2500 })); // listen to complete event goog.events.listen(request, "complete", function(){ if (request.isSuccess()) { // inject response into the dom goog.dom.$("response").innerHTML = request.getResponseText(); // print confirm to the console console.log("Satus code: ", request.getStatus(), " - ", request.getStatusText()); } else { // print error info to the console console.log( "Something went wrong in the ajax call. Error code: ", request.getLastErrorCode(), " - message: ", request.getLastError() ); } }); // start the request by setting POST method and passing // the data object converted to a queryString request.send("ajax-test.jsp", "POST", data.toString()); } |
| Print article | This entry was posted by Davide Zanotti on 17, Tuesday f, 2009 at 8:10 am, and is filed under google closure. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 8 months ago
Thanks!