Monday 6 October 2008

More than one way to skin a cat, continued...

Part 2: Loading external data into a web page using jQuery.

In part 1 we setup our ASP page to spit out random words on demand, so now we can start examining the various methods of getting the random words into our web pages.

Seeing as I am a jQuery nut, I'm going to demonstrate the jQuery way first (well, one of a few). If you've not played with jQuery yet, this might convince you to have a go.

Step 1: Include the jQuery library in the head of your web page
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
Step 2: Create a DIV in your page to contain the generated words
<div id="displayRandomWords"></div>
Step 3: Write the code to do the clever stuff..

Using your preferred text editor, create a new .js file and add the following code, then save it as jq_name_gen.js in the same directory as your html file.

// This is a basic "when everything is ready..."
$(document).ready(function(){

// This line tells jQuery to find an element with the ID 'displayRandomWords' and
// then to load the output from our ASP page into it. In one line of code!
$('#displayRandomWords').load('random_words.asp')
});

Step 4: Include your js in the head of your document

<script src="jq_name_gen.js" type="text/javascript"></script>

You should now have an HTML file that looks something like this...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script src="jq_name_gen.js" type="text/javascript"></script>
<title>Random words</title>
</head>
<body>
<div id="displayRandomWords"></div>
</body>
</html>
When you run the page in your web browser (on the server, as the ASP won't run locally remember!) you should see the random words magically appearing in your DIV. Click here to see it running.

Simple huh? To be honest, I have simplified things here to demonstrate some of the cool stuff without boring you with geeky stuff. Things to bear in mind include the fact that you can only load data from the documents parent domain (if you want to load from a different domain you will need a server-side proxy, check back soon for an example), and there is nothing in place to check to make sure the data has loaded. We'll cover that in a later tutorial, along with handling other types of data, including JSON and XML.

So, thats the first way of skinning our "loading external data" cat, in part 3 of this tutorial I will be using CSS and jQuery to make this widget a little more interesting.


Powered by ScribeFire.

No comments:

Post a Comment