Dojo.io.bind: Intro

From Dev411: The Code Wiki

dojo.io.bind is Dojo Toolkit (http://www.dojotoolkit.org)'s wrapper around XMLHttpRequest, similar to prototype's AJAX.Request. It has a few advantages over using straight XMLHttpRequest as well as other wrappers in that it is well designed and handles thing such as IE memory leaks (http://alex.dojotoolkit.org/?p=528). Here's an overview on using dojo.io.bind.

Table of contents

Overview

  • A dojo response has a type that is typically set to load or error, though sometimes it may be neither. With dojo, type=="load" means success.
  • Dojo.io.bind has a few handlers to process the response. The load handler is executed when the response type=="load" and the error handler is executed when the response type=="error". There is also a catch-all handle handler that can accept all response types so you can process a response that has a type that's neither load nor error.
  • If request parameters are set as a hash using content, dojo.io.bind will automatically turn them into form post parameters
  • The request headers can by setting headers to a hash
  • The response mimetype (or content-type) is set in the client JavaScript. Dojo uses this to determine how to process the response. Dojo ignores content-types set by the server

Post Parameters

Dojo.io.bind will automatically turn a hash (aka associative array or dictionary) into form POST paramters if content is set:

dojo.io.bind({
    url: "/ajax/login",
    method: "post",
    content: {username: "George", password: "curious"},
    load: function(type,data,evt) {
        alert("successful login");
    },
    mimetype: 'text/html'
});

JSON

Dojo.io.bind will expect a JSON string in the response body and auto-eval it if the mimetype is set to text/json on the client. In the following example, data is auto-evaled and turned into a JavaScript hash.

dojo.io.bind({
    url: "/binduri",
    method: "post",
    load: function(type,data,evt) {
        if (data.myItem)
            alert('Response JSON Item: '
            +data.myItem);
        }
    },
    mimetype: 'text/json'
});

Request Headers

You can set request headers by setting headers to a hash.

dojo.io.bind({
    url: '/ajax/login',
    method: 'post',
    load: function(type,data,evt) {
        alert("successful login");
    },
    mimetype: 'text/html',
    headers: { isDojo : true }
});
While setting a dojo header flag to true is common, I prefer more information and perhaps something more generic (though still non-standard) such as:
headers: { 'dojo-version' : dojo.version }
headers: { 'AJAX_USER_AGENT' : 'Dojo/' +  dojo.version }