AJAX - The Complete Reference

(avery) #1

172 Part I: Core Ideas


oNc7sN2TnzM8zz1Bwh8Q+kPEJiaCBNoKEIVDaWheGHRSmmltFI8Aq0Uj1OaKdPntP7FUsuPXnH3
qriWXNQpNHRjffH/hTKK/ilQhri8HQrr2RHw7mukfXb41L9lj33W6kP4HwoFGHEYwy8+06zyAr
qI/GixqJS61TOVEmtJi70DCiy06jF7JMyRK9wTiiSVKeXyUGpLrmb5Myjc32rv+MX8XsdwMe8g
9aM7zKW5Qj2nxOGN+2NZRmNDZzEX67X5oAxCcPYve4N1M6zZc0qhcJ5Bi5BnPAV8IjxfNrcqi2
eRLOdXbBjoHIIinwAoxTy8wDiAyssGTFLS9VLO5ysl81SRDgWgE6Gwoo/aBzCzIOvYK5LPIcIC
ibBMpZhQqn7QTr/fGGxCKVI5kzF3k60ii3OWRXNBVMO/pCtFPw2lobzekEGEbUwfP1P4PFLcW8
8gOUo5QWCIymzetA+4TzY2/GIx9mqO28td1lDEIxuDUlvxcooYOLw5B4rb7P+ETHlCoPwMkHs/
8327ayiHg3Yf+Mvd9QXKND53ovXqRQAAAABJRU5ErkJggg==" width="92" height="37">

And it could just easily be used in a style sheet rule as well:

ul.checklist {list-style-image:
url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAA
ABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeN
Ge4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC); }

NNOT EOTE While all the examples presented thus far focus on image data, there is nothing keeping you
from sending an arbitrary data format with such a URL. For example <link rel="stylesheet"
href="data:text/css;charset=utf-8, body%7Bbackground-color%3A%20red%7D"
media="screen" /> would create a linked style sheet to set the background red.

If you have the server send back an image encoded in base64 format, you can insert it
into the page as a data: URI. In PHP at least creating a base64 version of an existing image
is quite easy:

<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
$image = "path to the image in question";
$imageData = file_get_contents($image);
$image64 = base64_encode($imageData);
print $image64;
?>

You could make an XHR request to select or generate an image in the data: URI
format. When you receive a response, you then form a data: URI from the responseText
and set the src attribute of the <img> tag you wish to display, or create one from scratch
using DOM methods.

if (xhr.readyState == 4 && xhr.status == 200)
{
// responseImage is some <img> tag in the document
var responseImage = document.getElementById("responseImage");
responseImage.src = "data:image/png;base64," + xhr.responseText;
responseImage.style.display = "";
}

A simple example of data: URIs being used with XHRs can be found at http://ajaxref
.com/ch4/datauri.html. Just remember, it will not work in Internet Explorer browsers at
this point.
Free download pdf