AJAX - The Complete Reference

(avery) #1

140 Part I: Core Ideas


Encoded Text
As the final example of the endless possibilities for data formats in an Ajax application, we
present an encoded text format. If you are concerned with a data transmission being
immediately understood by visual inspection, you may decide to encode it. There are a
number of ways to encode data. Here we apply a simple base64 encoding to the payload
that underneath will be the standard x-www-form-urlencoded scheme.

var payload = encode64("rating=" + escapeValue(ratingVal) + "&comment=" +
escapeValue(comment));

The function encode64() is the implementation of the base64 encoding scheme and is
shown here:

function encode64(inputStr)
{
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var outputStr = "";
var i = 0;
while (i<inputStr.length)
{
var byte1 = inputStr.charCodeAt(i++);
var byte2 = inputStr.charCodeAt(i++);
var byte3 = inputStr.charCodeAt(i++);
var enc1 = byte1 >> 2;
var enc2 = ((byte1 & 3) << 4) | (byte2 >> 4);
var enc3, enc4;
if (isNaN(byte2))
enc3 = enc4 = 64;
else
{
enc3 = ((byte2 & 15) << 2) | (byte3 >> 6);
if (isNaN(byte3))
enc4 = 64;
else
enc4 = byte3 & 63;
}
outputStr += b64.charAt(enc1) + b64.charAt(enc2) + b64.charAt(enc3)
+ b64.charAt(enc4);
}
return outputStr;
}

Unlike the previous examples, this is just a matter of setting Content-Type and sending
the request on its way. In this case, the Content-Type header is set to be text/plain, and
in addition, the Content-Transfer-Encoding header is set to base64.

xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader("Content-Transfer-Encoding", "base64");

When the example at http://ajaxref.com/ch4/base64request.html is run, you should
see a network trace that looks similar to this:
Free download pdf