Tải bản đầy đủ - 0 (trang)
Chapter 19. Using YUI for Ajax and More

Chapter 19. Using YUI for Ajax and More

Tải bản đầy đủ - 0trang


Download at Boykma.Com


Web address

Spry Framework




Because each of these frameworks works differently, I have opted to settle on just one

of them—the YUI framework—for this chapter. I made this decision because it was

originally written by programmers at Yahoo!, which since then has allowed the JavaScript community as a whole to contribute code to the project. As a result, it’s a solid

framework used across all the Yahoo! properties and also by tens of thousands of developers around the world.

What’s more, you can download the entire framework and an extensive collection of

more than 300 example programs, along with a comprehensive amount of documentation, amounting to over 70 MB of data once uncompressed. But although I say “you

can,” you don’t have to, because all of these scripts and the documentation appear on

the YUI developer website, and you are permitted to simply link to each YUI script

directly from Yahoo’s servers.

Using YUI

To get started with YUI, visit the following URL to download the complete distribution

to your hard disk, where you can work on it locally:


The download is about 11 MB in size and is supplied as a ZIP file that you will need to

decompress. Once this is done, you will have a folder with a name such as

yui_2.7.0b, depending on the version downloaded, inside of which will be another

folder simply called yui.

Navigate to this folder and load up the index.html file that you’ll find there into your

browser to see a web page like that shown in Figure 19-1.

In the same directory where index.html resides, you’ll also see a number of others. In

particular I’d like to point you in the direction of the build folder, which contains about

60 subfolders that hold all the framework scripts (see Figure 19-2). You can copy the

ones you need from here directly to your website, or access the ones on Yahoo’s website

by referencing http://yui.yahooapis.com/2.7.0/build/ followed by the folder and script

name. (Without the latter two names, this URL will call up an error page.)

For example, you could copy the file yahoo.js from the build/yahoo folder to your website and link to it like this:

Or you could link directly to Yahoo’s copy, like this:

394 | Chapter 19: Using YUI for Ajax and More


Download at Boykma.Com

Figure 19-1. The YUI documentation main page

Figure 19-2. The build folder, which contains the .js framework files

Using YUI | 395


Download at Boykma.Com

If you link directly, make sure to change the version folder name from 2.7.0 if you are

using a newer version of YUI.

Compressed Versions

If you wish to speed up loading of these framework files, you can use the alternate

“min” versions Yahoo! supplies. For example, yahoo.js is about 33 KB in size, but there

is a file called yahoo-min.js that acts identically; by simply removing unnecessary

whitespace and other text, the developers have compressed it down to under 6 KB in

size. (There are tools on the Internet that let you minimize your own scripts, in case

you think doing so will speed up loading significantly.)

Using YUI for Ajax

In the previous chapter, we used XMLHttpRequest objects to provide Ajax connectivity

between the web browser, a server, and a third-party server. The process wasn’t too

difficult, but it was a bit fiddly due to differences between implementations in different


With YUI, handling Ajax becomes a whole lot easier, because it provides a range of

cross-browser methods that will work on any major browser. What’s more, they remove the need for you to output headers and perform other bits and pieces for POST

requests, and so on.

The upshot is that you can replace about 35 lines of code with a dozen or less. This

makes your programs much easier to write and debug, and removes all the lower-level

stuff, leaving it up to YUI to deal with.

Including the framework files

To perform Ajax calls with YUI, you need to include the following three framework

files (I have chosen to use the compressed versions for speed):


The main YUI file, generally required


The event handling framework file, used here for the callback


The Ajax handling framework file

If you copy those files from the relevant subfolders within the build folder to your web

folder, your program can load the files using the following code:

396 | Chapter 19: Using YUI for Ajax and More


Download at Boykma.Com

Or you can fetch them directly from Yahoo’s website using the following code:

The YUI asyncRequest method

Now all you need to do is call asyncRequest, Yahoo’s version of the ajaxRequest function

we created in the last chapter. The syntax is:

YAHOO.util.Connect.asyncRequest('method', 'url', callback [, 'parameters...'])

The method to use is either POST or GET; the url should be a PHP script on your server.

If you’re using the GET method, the name of the script should be followed by a ? and

the parameter/value pairs you wish to send. The callback needs to point to a pair of

functions to handle either successful completion or failure, and the parameters are

passed only when you are using the POST method and the target server requires parameters for the request.

So an Ajax GET request might look like this:

YAHOO.util.Connect.asyncRequest('GET', 'program.php', callback)

The callback object should be created like this:

callback = { success:successHandler, failure:failureHandler }

The successHandler and failureHandler functions should contain instructions for your

program to execute according to the intention of your project.

An Ajax GET example using YUI

Let’s take Example 18-4 from the previous chapter and see what it looks like when

modified to use YUI (see Example 19-1, yuiurlget.html).

Example 19-1. yuiurlget.html

YUI GET Example

Loading a web page into a DIV with YUI

This sentence will be replaced

I’m sure you’ll agree that this is very simple indeed. After setting up the web page,

displaying a heading, and creating the DIV in which to place the Ajax response, the

program loads three YUI framework files. The rest of the document (less than 10 lines

of code) is the Ajax, which does the following:

1. Place the URL to fetch, yahoo.com, in the variable url.

2. Create the callback object. This is an associative array that points to the handlers

to be called in case of the success or failure of the call.

3. Place the Ajax call, which is a GET request to the URL urlget.php?url=yahoo.com.

You may recall that we wrote urlget.php in the previous chapter (Example 18-5) and,

as it doesn’t require modifying, I won’t repeat it here. Suffice it to say that the program

fetches the HTML page at http://yahoo.com and returns it to the Ajax method.

All that remains are the two functions for success or failure of the call. The success

function, successHandler, simply places the Ajax response text into the DIV that we

prepared for it, and failureHandler displays an appropriate message upon error.

The result of calling up this new document in your browser can be seen in Figure 19-3.

Figure 19-3. The result of calling up yuiurlget.html in a browser

398 | Chapter 19: Using YUI for Ajax and More


Download at Boykma.Com

An Ajax XML example using YUI

Now let’s see how you can use the asyncRequest method with XML by calling up the

Yahoo! RSS weather feed for Washington, D.C., using Example 19-2, yuixmlget.html.

Example 19-2. yuixmlget.html

YUI XML Example

Loading XML content into a DIV with YUI

This sentence will be replaced

This document is fairly similar to the previous one, in that the same YUI framework

scripts are included, but right away, you’ll notice that the url is different. Because the

weather feed itself takes GET parameters using a ? symbol, we have to URI-encode it as


url = encodeURI("xml.weather.yahoo.com/forecastrss?p=20500")

This encoding has the effect of turning any special characters into a form that will not

confuse the PHP program into thinking that additional parameters have been passed.

Next, you’ll see that the callback object is the same as before, so we’ll gloss over that

and move on to the request, which has only a name change from urlget.php to

xmlget.php in order to call the correct PHP program for XML. The xmlget.php program

is the same one we created in the previous chapter (see Example 18-6) and thus doesn’t

need repeating here.

Using YUI | 399


Download at Boykma.Com

Figure 19-4. The result of calling up yuixmlget.html in a browser

You’ll also notice that the function failureHandler is identical. So the main remaining

change is in successHandler. This function refers to responseXML instead of

responseText, from which it extracts the title, date, and text from the RSS feed and

then inserts them into the DIV we prepared. The result of calling up yuixmlget.html

into a browser can be seen in Figure 19-4.

Other Uses for YUI

The YUI framework offers support in a wide range of areas, including animation, buttons, calendars, charts, colors, cookies, drag and drop, fonts, imaging, menus, styles,

uploading, and a great deal more as well.

To find features you need, check out the examples down the left of the main

index.html page in the downloaded distribution or at http://developer.yahoo.com/yui

and click on ones that interest you.

400 | Chapter 19: Using YUI for Ajax and More


Download at Boykma.Com

A Simple YUI Calendar

For example, clicking through to the calendar link reveals how you can make your own

calendars, a common feature needed by many websites. Here’s how you can recreate

the calendar example shown at:


To do so, locate all the following files in the build folder of the downloaded YUI distribution on your hard disk, and copy them to your web folder (bearing in mind that

assets is a folder, not a file):



yahoo-dom-event /yahoo-dom-event.js


Now you can type in the document in Example 19-3, calendar.html, which, when you

call it up in your browser, will look like Figure 19-5.

Figure 19-5. A YUI calendar

Other Uses for YUI | 401


Download at Boykma.Com

Example 19-3. calendar.html—a multiselect calendar

YUI Calendar

type="text/css" href="fonts-min.css" />

type="text/css" href="assets/skins/sam/calendar.css" />

All that remains to do is place the following DIV where you want it on your web page,

and the calendar will appear there:

You can also link directly to the various files on the Yahoo! server by modifying the

three lines that link to the YUI libraries to read as follows:

href="http://yui.yahooapis.com/2.7.0/build/calendar/assets/skins/sam/calendar.css" />

All the other YUI features are just as easy to use, and require you only

to carefully read the accompanying documentation before copying and

pasting the supplied code. There’s even a link to the YUI Dependency

Configurator supplied with each example, which will build a copy-andpaste script to load all the dependent JavaScript and CSS files for any

feature, directly from the Yahoo! servers.

I hope you have a lot of fun using the resources supplied by YUI (and any of the other

frameworks you try). If you do, you’ll find yourself saved from reinventing the wheel

time and time again.

402 | Chapter 19: Using YUI for Ajax and More


Download at Boykma.Com

In the next and final chapter I’ll bring everything you’ve learned so far together into a

social networking application.

Test Your Knowledge: Questions

Question 19-1

What is YUI’s method of implementing an Ajax connection?

Question 19-2

Write a callback object for YUI called callback to reference a success handler called

succeeded and a failure handler called failed.

Question 19-3

Write a GET call to asyncRequest that references the program getdata.php and a

callback object.

Question 19-4

How can you encode the URL mysite.com/message?m=123, which contains the ?

symbol, so that if sent as a GET request it will be treated just as a string and not


See the section “Chapter 19 Answers” on page 451 in Appendix A for the answers to

these questions.

Test Your Knowledge: Questions | 403


Download at Boykma.Com

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 19. Using YUI for Ajax and More

Tải bản đầy đủ ngay(0 tr)