Our Ajax application has fetched information from the server and then parsed the data and acted upon it. Now we'll show you how to make the application retrieve a new version of the data from the server, which automatically refreshes the page. Script 15.7 contains the necessary JavaScript.
| 1. | function getPix() { xhr.open("GET", "flickrfeed.xml", true); xhr.onreadystatechange = showPictures; xhr.send(null); setTimeout("getPix()",5 * 1000); } Where the previous script did the xhr call inside initAll() , this script pushes it down into its own function, getPix() . There's one addition: the setTimeout() afterwards. Five seconds after the script has grabbed a random image, it goes and gets another. |
| 2. | for (var i=1; i<allLinks.length; i+=2) { tempDiv2.appendChild(allLinks[i]. cloneNode(true)); } This is almost the same loop that's in the previous task, with one difference: instead of appending the nodes to the Web page, it adds them to another temporary div . |
| | |
| 3. | allLinks = tempDiv2. getElementsByTagName("a"); var randomImg = Math.floor (Math.random() * allLinks.length); document.getElementById ("pictureBar").innerHTML = allLinks[randomImg].innerHTML; When the loop completes, we want to figure out one random image out of all of them to display. We start by creating another array of links (now with just the linked photographs instead of all the links). We then calculate a random number between zero and one less than the number of images, using Math.random() and Math.floor() as we did back in Chapter 4 in "Displaying a Random Image." And finally, we use that random number as an index into the allLinks array to grab the one image, and we put that into our Web page ( Figure 15.4 ). Figure 15.4. The script fetches one image after another. |