1. Trang chủ
  2. » Công Nghệ Thông Tin

build your own ajax web applications PHẦN 4 pot

32 178 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Build Your Own Ajax Web Applications Phần 4 Pot
Trường học University of Technology
Chuyên ngành Web Development
Thể loại Bài luận
Năm xuất bản 2023
Thành phố Hanoi
Định dạng
Số trang 32
Dung lượng 542,27 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Running the Animation The code for the processing animation consists of five methods: the first threecontrol the “Processing …” animation, while the remaining two control the “Done”anima

Trang 1

Opacity in Opera?

Unfortunately, at the time of writing, even the latest version of Opera (version 8.5) doesn’t support CSS opacity, so such an animation does not work in that browser However, this feature is planned for Opera version 9.

Running the Animation

The code for the processing animation consists of five methods: the first threecontrol the “Processing …” animation, while the remaining two control the “Done”animation The three methods that control the “Processing …” animation are:

❑ startProc, which sets up the “Processing …” animation and schedules peated calls to doProc with setInterval

re-❑ doProc, which monitors the properties of this class and sets the current frame

of the “Processing …” animation appropriately

❑ stopProc, which signals that the “Processing …” animation should ceaseThe two that control the “Done” animation are:

❑ startDone sets up the “Done” animation and schedules repeated calls to

doDone with setInterval

❑ doDone sets the current frame of the “Done” animation and terminates theanimation once it’s completed

Starting it Up

Setting the animation up and starting it are jobs for the startProcmethod:

File: appmonitor2.js (excerpt)

this.startProc = function() { var self = Status;

self.proc = 'proc';

if (self.setDisplay(false)) { self.currOpacity = 100;

self.displayOpacity();

self.procInterval = setInterval(self.doProc, 90);

} };

Running the Animation

Trang 2

After setting the proc property to proc (processing), this code calls the

setDisplay method, which sets the color and content of the pollingMessage div We’ll take a closer look at setDisplay next

Once the code sets the color and content of the pollingMessage div, it initializesthe div’s opacity to 100 (completely opaque) and calls displayOpacity to makethis setting take effect

Finally, this method calls setInterval to schedule the next step of the animationprocess Note that, as with setTimeout, the setInterval call returns an interval

ID We store this in the procInterval property so we can stop the process later.Both the “Processing …” and “Done” animations share the setDisplay method:

File: appmonitor2.js (excerpt)

Since the only differences between the “Processing …” and “Done” states of the

pollingMessage div are its color and text, it makes sense to use this commonfunction to toggle between the two states of the pollingMessage div The colorsare controlled by assigning classes to the pollingMessage div, so we’ll need toadd CSS class rules for the done and processing classes to our style sheet:

File: appmonitor2.css (excerpt)

Trang 3

.done { color:#393;

it in the natural break, when the “Processing …” image’s opacity is down to zero

So the stopProcmethod for stopping the animation doesn’t actually stop it perse—it just sets a flag to tell the animation process that it’s time to stop when itreaches a convenient point This is a lot like the phone calls received by manyprogrammers at the end of the day from wives and husbands reminding them tocome home when they get to a logical stopping point in their code

Since very little action occurs here, the method is pretty short:

File: appmonitor2.js (excerpt)

this.stopProc = function(done) { var self = Status;

if (done) { self.proc = 'done';

} else { self.proc = 'abort';

} };

This method does have to distinguish between two types of stopping: a successfullycompleted request (done) and a request from the user to stop the application(abort)

The doProc method uses this flag to figure out whether to display the “Done”message, or just to stop

Running the Animation with doProc

The doProc method, which is invoked at 90 millisecond intervals, changes theopacity of the pollingMessage div to produce the pulsing effect of the processinganimation Here’s the code:

Running the Animation

Trang 4

File: appmonitor2.js (excerpt)

(fully opaque) Executing this code every 90 milliseconds produces a smooth effect

in which the pollingMessage div fades out, reappears, and fades out again—thefamiliar pulsing effect that shows that the application is busy doing something

If the animation is not supposed to continue running, we stop the animation bycalling clearInterval, then, if the proc property is done, we trigger the “Done”animation with a call to startDone

Starting the “Done” Animation with startDone

The startDonemethod serves the same purpose for the “Done” animation thatthe startProc method serves for the “Processing …” animation It looks remark-ably similar to startProc, too:

File: appmonitor2.js (excerpt)

Trang 5

self.procInterval = setInterval(self.doDone, 90);

} };

This time, we pass true to setDisplay, which will change the text to “Done”and the color to green

We then set up calls to doDone with setInterval, which actually performs thefadeout

The Final Fade

The code for doDone is significantly simpler than the code for doProc It doesn’thave to process continuously until told to stop, like doProc does It just keeps

on reducing the opacity of the pollingMessage div by 10% until it reaches zero,then stops itself Pretty simple stuff:

File: appmonitor2.js (excerpt)

this.doDone = function() { var self = Status;

if (self.currOpacity == 0) { clearInterval(self.procInterval);

} self.currOpacity = self.currOpacity - 10;

self.displayOpacity();

};

Running the Animation

Trang 6

Figure 3.9 The application with a pulsing status indicator

Finally, we’re ready to test this code in our browser Open appmonitor2.html inyour browser, click the Start button, and you should see a pulsing Processing message near the top right-hand corner of the browser’s viewport, like the oneshown in Figure 3.9

Be Careful with that Poll Interval!

Now that we have an animation running in the page, we need to be careful that we don’t start the animation again before the previous one stops For this reason, it’s highly recommended that you don’t set POLL_INTERVAL to anything less than two seconds.

Styling the Monitor

Now that we’ve got our application up and running, let’s use CSS to make it lookgood We’ll need to add the following markup to achieve our desired layout:Chapter 3: The “A” in AJAX

Trang 7

File: appmonitor2.html (excerpt)

As you can see, we’ve added three divs from which we can hang our styles, and

a line break to clear the floated application status message and animation Thecompleted CSS for this page is as follows; the styled interface is shown in Fig-ure 3.10:

File: appmonitor2.css

body, p, div, td, ul { font-family: verdana, arial, helvetica, sans-serif;

font-size:12px;

}

#wrapper { padding-top: 24px;

}

#main { width: 360px;

Trang 8

border: 1px solid #ddd; }

.done {

color: #393;

border: 1px solid #393; }

Trang 9

.inputButton { width: 8em;

height: 2em;

} clearBoth { clear: both;

Summary

Trang 10

ity was our use of setTimeout to time the XMLHttpRequest requests This exampleprovided a good opportunity to explore some of the common problems you’llencounter as you develop AJAX apps, such as loss of scope and connectiontimeouts, and provided practical solutions to help you deal with them.

Chapter 3: The “A” in AJAX

Trang 11

AJAX and POST Requests

4

I do not sit at the kiddie table Now you either give me the big toys or you send me home.

—John Crichton, Farscape

We spent the last two chapters working with AJAX and basic HTTP GET requests

We built a very simple monitoring application that pings a web site and reportsthe server’s response time In this chapter, we’ll move up to the next level as webegin to work with POST requests Here, we’ll build a web application login screenthat uses AJAX to send users’ login information back to the server in a POST re-quest

Generally, a login page for a web application involves only two form fields, soit’s legitimate to ask if there’s any real advantage in using AJAX techniques tobuild such a form Why wouldn’t we just keep things basic and use a normalform? Actually, this is a very important question AJAX development is fairlynew, and right now the biggest problem with it seems to be that people immedi-

ately begin to ask how to achieve a task using AJAX when they should first ask if

they should achieve that task using AJAX

You should only pull AJAX out of your web development toolbox if it’s going toprovide tangible value for the end user In the case of a web application loginsystem, AJAX can deliver some real benefits in terms of efficiency and ease ofuse With the login form we’ll be building in this chapter, incomplete form sub-missions are near-impossible, and incorrect logins can be reported in as little time

Trang 12

as it takes to send and receive a few hundred bytes of data This is a big ment on the tens of thousands of bytes that would need to be sent and received

improve-in an non-AJAX web application

But, before we dive into the process of POSTing data, let’s review how we workwith query strings, and how we send data back to the server with the request

Review: Sending Data with GET

An easy way to send a little data back to the server involves sending a simple GET

request with a query string tacked onto the end of the target URL Doing so usingour Ajax library is easy:

var ajax = new Ajax();

var handlerFunc = function(str) {

// Do something with the response

}

ajax.doGet('/some_url.php?bass=Geddy&guitar=Alex&drums=Neil', handlerFunc);

Using GET makes it very easy to send a little extra information to the web server

Sending Data with POST

Let’s have a look at how our Ajax class sends POST requests, then apply that toour web application login

The POST method sends the extra data in a package that’s separate from the pagelocation, so it’s not as easy to use as GET However, it’s the preferred option inthe following types of situations:

❑ You need to send a large amount of data back to the server

❑ The data needs to be formatted in a very specific way (e.g., XML-RPC)

❑ You’re sending sensitive data such as passwords

We need to take the following, additional steps in order to use our Ajax class tosend POST requests:

❑ Set the request method for our instance of XMLHttpRequest to POST (ofcourse)

Chapter 4: AJAX and POST Requests

Trang 13

❑ Pass the POST data to the send method of the XMLHttpRequest object.

❑ Set the Content-Typeheader for the request to urlencoded

application/x-www-form-To perform these actions, we’ll add to the Ajax class a method called doPost,which will be very similar to doGet:

File: ajax.js (excerpt)

this.doPost = function(url, postData, hand, format) { this.url = url;

File: ajax.js (excerpt)

this.req.open(this.method, this.url, this.async);

In order to set the POST data for this request, we simply set the postDataproperty.This data should consist of a string that’s formatted in variable-value pairs and

is URL-encoded—just like a normal query string

Finally, we need to set the ContentType of the request to form-urlencoded We’ll add this to the doReq method using the

application/x-www-setRequestMethodmethod:

File: ajax.js (excerpt)

this.doReq = function() {

if (!this.init()) { alert('Could not create XMLHttpRequest object.');

return;

} this.req.open(this.method, this.url, this.async);

if (this.method == "POST") { this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Sending Data with POST

Trang 14

Now, let’s look at a quick example that pulls data from an actual form.

Imagine that you have a web page that displays the following form, which containsinformation about 80s-era progressive rock bands:

<form id="band" action="/handle_input.php">

<input type="text" name="bass" id="bass" value="Geddy"/>

<input type="text" name="guitar" id="guitar" value="Alex"/> <input type="text" name="drums" id="drums" value="Neil"/>

</form>

You could pull out the form data and POST it with our Ajax object, like this:

var bandForm = document.getElementById('band');

var ajax = new Ajax();

var handlerFunc = function(str) {

// Do something with the response

}

var formData = '';

formData += 'bass=' + escape(bandForm.bass.value);

formData += '&guitar=' + escape(bandForm.guitar.value);

formData += '&drums=' + escape(bandForm.drums.value);

ajax.doPost('/handle_input.php', formData, handlerFunc);

This seems fairly easy The only difference between this and the doGet method

is the extra parameter, which passes the query string-formatted data for POSTing

When you’re working with more complicated forms, you’re not very likely towant to craft query strings laboriously, pulling in the data from form elements.Chapter 4: AJAX and POST Requests

Trang 15

This is where formData2QueryString1 comes in handy formData2QueryString,

an external library, contains a handy function that scrapes a web form of all itsdata and creates a string of name-value pairs; we can use formData2QueryString

for our POST.Using formData2QueryString is easy: just pass it a reference to the form fromwhich you want to pull data, and it returns a properly formatted string thatcontains the values of all the elements in the form

Using formData2QueryString, we could modify the previous example to looklike this:

var bandForm = document.getElementById('band');

var ajax = new Ajax();

var handlerFunc = function(str) { // Do something with the input }

var formData = '';

formData = formData2QueryString(bandForm);

ajax.doPost('/handle_input.php', formData, handlerFunc);

formData2QueryString allows you to continue to use web forms as you alwayshave, while taking advantage of the power of AJAX

1 formData2QueryString is available under the Apache License, Version 2.0, at http://www.fleegix.org/downloads/formdata2querystring.js.

Using formData2QueryString

Trang 16

An Application Login

Figure 4.1 The web application login

By AJAX-ifying a web application’s login form you can provide your users an perience that’s much closer to that of a traditional desktop application than atypical web application AJAX improves the developer’s ability to insert notifica-tions—such as processing animations or error messages—inline into the page,which quickly and conveniently lets users know what’s happening with the loginprocess Figure 4.1 shows what the login page will look like

ex-Accessibility and Backward Compatibility

In some cases, AJAX web application code is so complicated that it makes sense

to maintain two separate versions—a “hi-fi” version that contains all the AJAXbells and whistles for modern browsers, and a low-fi version, made up of text-only web pages generated on the server side, for users of older browsers, textbrowsers, and low-end mobile devices This all-or-nothing approach is less thanoptimal, because it requires us to relegate all users who don’t have the idealbrowser configuration to the text-only “ghetto,” even though many of their systemsmay support a lot of the app’s functionality

That’s why the principle of progressive enhancement (which, in the web

applic-ation context, is also known as “unobtrusive DHTML”) should underpin thedesign of our code This principle proposes that we should build our app’s moreChapter 4: AJAX and POST Requests

Ngày đăng: 12/08/2014, 09:21

TỪ KHÓA LIÊN QUAN