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 271<br />

Figure 11-7. Viewing several pictures from the server with tags<br />

Writing the Forward-Caching Ajax Client<br />

The principle behind the forward-caching Ajax client is very straightforward. You keep<br />

track of the ID of the current image <strong>and</strong> provide buttons that allow you to add <strong>and</strong><br />

remove 1 from this ID. You then construct a URL to the image server, passing it the new<br />

ID <strong>and</strong> getting the response. Then you download the images that are 1 <strong>and</strong> 2 more than<br />

this value, as well as those that are 1 <strong>and</strong> 2 less than this value. When you call the URL<br />

<strong>and</strong> download the images, the browser will cache them.<br />

For example, if the current image is 100, <strong>and</strong> you move forward to 101, the page will<br />

construct a URL call to the server asking for 101. If this has already been called, the<br />

results will be cached, <strong>and</strong> the image loaded from the cache. It will also construct calls<br />

to 102, 103, 100, <strong>and</strong> 99, <strong>and</strong> put the responses in the browser cache.<br />

To do this, you need to use a slightly different technique from what you did in the<br />

simple example. You’ll use two XMLHttpRequest objects: one with a callback that renders<br />

the image, <strong>and</strong> one that doesn’t use a callback, but just gets the image <strong>and</strong> caches it.<br />

Add a new HTML page to your application <strong>and</strong> call it <strong>AJAX</strong>PictureClient.htm. Change<br />

the body of the application to contain a in which the image will be displayed, <strong>and</strong><br />

two buttons—one for moving forward <strong>and</strong> one for moving backward. Here’s the complete<br />

markup, including the JavaScript event-h<strong>and</strong>ler function calls that h<strong>and</strong>le loading the<br />

page <strong>and</strong> clicking the buttons:<br />

<br />

<br />

<br />

<br />

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

Saved successfully!

Ooh no, something went wrong!