08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 11 ■ <strong>AJAX</strong> APPLICATIONS AND EMPOWERING THE WEB USER EXPERIENCE 273<br />

}<br />

ajaxRequest.onreadystatechange=DisplayPic;<br />

ajaxRequest.send();<br />

This is a simple Ajax function, constructing a URL to the GetPicture service using<br />

the value that was passed into it. It performs an HTTP-GET to that URL, <strong>and</strong> specifies<br />

DisplayPic as the callback function for state changes.<br />

The DisplayPic function then checks for readyState being 4 (i.e., download complete),<br />

<strong>and</strong> loads the with an tag pointing to the same URL. As the image<br />

has already been downloaded, it will be instantly pulled from the cache. Note that the<br />

browser looks at the URI of a resource <strong>and</strong> determines if the current version is cached.<br />

If it is, it loads it from the cache; if it isn’t, it downloads it.<br />

function DisplayPic()<br />

{<br />

var divPic = document.getElementById("pic");<br />

if(ajaxRequest.readyState == 4)<br />

{<br />

divPic.innerHTML = "";<br />

}<br />

GetPic(currentPic+1);<br />

GetPic(currentPic+2);<br />

GetPic(currentPic-1);<br />

GetPic(currentPic-2);<br />

}<br />

In addition to this, it also calls the GetPic function, which kicks in the second Ajax<br />

function. This simply downloads (but doesn’t display) the graphics. It calls this function<br />

four times, for currentPic+1, currentPic+2, currentPic-1, <strong>and</strong> currentPic-2. Many of these<br />

images will already be cached, so the call will be quick. This function could probably be a<br />

little smarter, but for the sake of simplicity, the brute-force method is used here.<br />

The GetPic function is a st<strong>and</strong>ard Ajax call, but no callback is needed, as the image<br />

will not be rendered.<br />

function GetPic(thisPic)<br />

{<br />

}<br />

theCachedURL = "GetPicture.aspxpicid=" + thisPic;<br />

cachedAjaxRequest.open("GET", theCachedURL);<br />

cachedAjaxRequest.send();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!