英文翻译

3995
    


来源:
Licence:
联系:
分类:
平台:
环境:
大小:
更新:
标签:
联系方式 :
免费下载 ×

下载APP,支持永久资源免费下载

限免产品服务请联系qq:1585269081

下载APP
免费下载 ×

下载APP,支持永久资源免费下载

下载APP 免费下载
下载 ×

下载APP,资源永久免费


如果出现不能下载的情况,请联系站长,联系方式在下方。

免费下载 ×

下载论文助手APP,资源永久免费

免费获取

如果你已经登录仍然出现不能下载的情况,请【点击刷新】本页面或者联系站长


Introduction to Ajax

By Brett McLaughlin

Five years ago, if you didn't know XML, you were the ugly duckling whom nobody talked to. Eighteen months ago, Ruby came into the limelight and programmers who didn't know what was going on with Ruby weren't welcome at the water cooler. Today, if you want to get into the latest technology rage, Ajax is where it's at.

However, Ajax is far more than just a fad; it's a powerful approach to building Web sites and it's not nearly as hard to learn as an entire new language.

Before I dig into what Ajax is, though, let's spend just a few moments understanding what Ajax does. When you write an application today, you have two basic choices:

1 Desktop applications

2 Web applications

These are both familiar; desktop applications usually come on a CD (or sometimes are downloaded from a Web site) and install completely on your computer. They might use the Internet to download updates, but the code that runs these applications resides on your desktop. Web applications -- and there's no surprise here -- run on a Web server somewhere and you access the application with your Web browser.

More important than where the code for these applications runs, though, is how the applications behave and how you interact with them. Desktop applications are usually pretty fast (they're running on your computer; you're not waiting on an Internet connection), have great user interfaces (usually interacting with your operating system), and are incredibly dynamic. You can click, point, type, pull up menus and sub-menus, and cruise around, with almost no waiting around.

On the other hand, Web applications are usually up-to-the-second current and they provide services you could never get on your desktop (think about Amazon.com and eBay). However, with the power of the Web comes waiting -- waiting for a server to respond, waiting for a screen to refresh, waiting for a request to come back and generate a new page.

Obviously this is a bit of an oversimplification, but you get the basic idea. As you might already be suspecting, Ajax attempts to bridge the gap between the functionality and interactivity of a desktop application and the always-updated Web application. You can use dynamic user interfaces and fancier controls like you'd find on a desktop application, but it's available to you on a Web application.

So what are you waiting for? Start looking at Ajax and how to turn your clunky Web interfaces into responsive Ajax applications.

Old technology, new tricks

When it comes to Ajax, the reality is that it involves a lot of technologies -- to get beyond the basics, you need to drill down into several different technologies (which is why I'll spend the first several articles in this series breaking apart each one of them). The good news is that you might already know a decent bit about many of these technologies -- better yet, most of these individual technologies are easy to learn -- certainly not as difficult as an entire programming language like Java or Ruby.

Ajax defined

By the way, Ajax is shorthand for Asynchronous JavaScript and XML (and DHTML, and so on). The phrase was coined by Jesse James Garrett of Adaptive Path (see the HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "resources#resources" Resources section) and is, according to Jesse, not meant to be an acronym.

Here are the basic technologies involved in Ajax applications:

1 HTML is used to build Web forms and identify fields for use in the rest of your application.

JavaScript code is the core code running Ajax applications and it helps facilitate communication with server applications.

DHTML, or Dynamic HTML, helps you update your forms dynamically. You'll use div, span, and other dynamic HTML elements to mark up your HTML.

DOM, the Document Object Model, will be used (through JavaScript code) to work with both the structure of your HTML and (in some cases) XML returned from the server.

Let's break these down and get a better idea of what each does. I'll delve into each of these more in future articles; for now focus on becoming familiar with these components and technologies. The more familiar you are with this code, the easier it will be to move from casual knowledge about these technologies to mastering each (and really blowing the doors off of your Web application development).

The XMLHttpRequest object

The first object you want to understand is probably the one that's newest to you; it's called XMLHttpRequest. This is a JavaScript object and is created as simply as shown in HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code1#code1" Listing 1.Listing 1. Create a new XMLHttpRequest object




I'll talk more about this object in the next article, but for now realize that this is the object that handles all your server communication. Before you go forward, stop and think about that -- it's the JavaScript technology through the XMLHttpRequest object that talks to the server. That's not the normal application flow and it's where Ajax gets much of its magic.

In a normal Web application, users fill out form fields and click a Submit button. Then, the entire form is sent to the server, the server passes on processing to a script (usually PHP or Java or maybe a CGI process or something similar), and when the script is done, it sends back a completely new page. That page might be HTML with a new form with some data filled in or it might be a confirmation or perhaps a page with certain options selected based on data entered in the original form. Of course, while the script or program on the server is processing and returning a new form, users have to wait. Their screen will go blank and then be redrawn as data comes back from the server. This is where low interactivity comes into play -- users don't get instant feedback and they certainly don't feel like they're working on a desktop application.

Ajax essentially puts JavaScript technology and the XMLHttpRequest object between your Web form and the server. When users fill out forms, that data is sent to some JavaScript code and not directly to the server. Instead, the JavaScript code grabs the form data and sends a request to the server. While this is happening, the form on the users screen doesn't flash, blink, disappear, or stall. In other words, the JavaScript code sends the request behind the scenes; the user doesn't even realize that the request is being made. Even better, the request is sent asynchronously, which means that your JavaScript code (and the user) doesn't wait around on the server to respond. So users can continue entering data, scrolling around, and using the application.

Then, the server sends data back to your JavaScript code (still standing in for the Web form) which decides what to do with that data. It can update form fields on the fly, giving that immediate feeling to your application -- users are getting new data without their form being submitted or refreshed. The JavaScript code could even get the data, perform some calculations, and send another request, all without user intervention! This is the power of XMLHttpRequest. It can talk back and forth with a server all it wants, without the user ever knowing about what's really going on. The result is a dynamic, responsive, highly-interactive experience like a desktop application, but with all the power of the Internet behind it.

Adding in some JavaScript

Once you get a handle on XMLHttpRequest, the rest of your JavaScript code turns out to be pretty mundane. In fact, you'll use JavaScript code for just a few basic tasks:

Get form data: JavaScript code makes it simple to pull data out of your HTML form and send it to the server.

Change values on the form: It's also simple to update a form, from setting field values to replacing images on the fly.

Parse HTML and XML: You'll use JavaScript code to manipulate the DOM (see the HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "dom#dom" next section) and to work with the structure of your HTML form and any XML data that the server returns.

For those first two items, you want to be very familiar with the getElementById() method as shown in HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code2#code2" Listing 2.Listing 2. Grab and set field values with JavaScript code



// Get the value of the "phone" field and stuff it in a variable called phone

var phone = document.getElementById("phone").value;
// Set some values on a form using an array called response

document.getElementById("order").value = response[0];

document.getElementById("address").value = response[1];
There's nothing particularly remarkable here and that's good! You should start to realize that there's nothing tremendously complicated about this. Once you master XMLHttpRequest, much of the rest of your Ajax application will be simple JavaScript code like that shown in HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code2#code2" Listing 2, mixed in with a bit of clever HTML. Then, every once in a while, there's a little DOM work...so let's look at that.

Finishing off with the DOM

Last but not least, there's the DOM, the Document Object Model. For some of you, hearing about the DOM is going to be a little intimidating -- it's not often used by HTML designers and is even somewhat unusual for JavaScript coders unless you're really into some high-end programming tasks. Where you will find the DOM in use a lot is in heavy-duty Java and C/C++ programs; in fact, that's probably where the DOM got a bit of its reputation for being difficult or hard to learn.

Fortunately, using the DOM in JavaScript technology is easy, and is mostly intuitive. At this point, I'd normally show you how to use the DOM or at least give you a few code examples, but even that would be misleading. You see, you can get pretty far into Ajax without having to mess with the DOM and that's the path I'm going to show you. I'll come back to the DOM in a future article, but for now, just know that it's out there. When you start to send XML back and forth between your JavaScript code and the server and really change the HTML form, you'll dig back into DOM. For now, it's easy to get some effective Ajax going without it, so put this on the back-burner for now.
Getting a Request object

With a basic overview under your belt, you're ready to look at a few specifics. Since XMLHttpRequest is central to Ajax applications -- and probably new to many of you -- I'll start there. As you saw in HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code1#code1" Listing 1, it should be pretty easy to create this object and use it, right? Wait a minute.

Remember those pesky browser wars from a few years back and how nothing worked the same across browsers? Well, believe it or not, those wars are still going on albeit on a much smaller scale. And, surprise: XMLHttpRequest is one of the victims of this war. So you'll need to do a few different things to get an XMLHttpRequest object going. I'll take your through it step by step.

Working with Microsoft browsers

Microsoft's browser, Internet Explorer, uses the MSXML parser for handling XML (you can find out more about MSXML in HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "resources#resources" Resources). So when you write Ajax applications that need to work on Internet Explorer, you need to create the object in a particular way.

However, it's not that easy. MSXML actually has two different versions floating around depending on the version of JavaScript technology installed in Internet Explorer, so you've got to write code that handles both cases. Look at HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code3#code3" Listing 3 for the code that you need to create an XMLHttpRequest on Microsoft browsers.Listing 3. Create an XMLHttpRequest object on Microsoft browsers



var xmlHttp = false;

try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e2) {

xmlHttp = false;

}

}
All of this won't make exact sense yet, but that's OK. You'll dig into JavaScript programming, error handling, conditional compilation, and more before this series is finished. For now, you want to get two core lines into your head:

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

and

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");.

In a nutshell, this code tries to create the object using one version of MSXML; if that fails, it then creates the object using the other version. Nice, huh? If neither of these work, the xmlHttp variable is set to false, to tell your code know that something hasn't worked. If that's the case, you've probably got a non-Microsoft browser and need to use different code to do the job.

Dealing with Mozilla and non-Microsoft browsers

If Internet Explorer isn't your browser of choice or you write code for non-Microsoft browsers, then you need different code. In fact, this is the really simple line of code you saw back in HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code1#code1" Listing 1:

var xmlHttp = new XMLHttpRequest object;.

This much simpler line creates an XMLHttpRequest object in Mozilla, Firefox, Safari, Opera, and pretty much every other non-Microsoft browser that supports Ajax in any form or fashion.

Putting it together

The key is to support all browsers. Who wants to write an application that works just on Internet Explorer or an application that works just on non-Microsoft browsers? Worse yet, do you want to write your application twice? Of course not! So your code combines support for both Internet Explorerand non-Microsoft browsers. HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code4#code4" Listing 4 shows the code to do just that.Listing 4. Create an XMLHttpRequest object the multi-browser way



/* Create a new XMLHttpRequest object to talk to the Web server */

var xmlHttp = false;

/*@cc_on @*/

/*@if (@_jscript_version >= 5)

try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e2) {

xmlHttp = false;

}

}

@end @*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {

xmlHttp = new XMLHttpRequest();

}
For now, ignore the commenting and weird tags like @cc_on; those are special JavaScript compiler commands that you'll explore in depth in my next article, which will focus exclusively on XMLHttpRequest. The core of this code breaks down into three steps:

Create a variable, xmlHttp, to reference the XMLHttpRequest object that you will create.

Try and create the object in Microsoft browsers:

Try and create the object using the Msxml2.XMLHTTP object.

If that fails, try and create the object using the Microsoft.XMLHTTP object.

If xmlHttp still isn't set up, create the object in a non-Microsoft way.

At the end of this process, xmlHttp should reference a valid XMLHttpRequest object, no matter what browser your users run.

A word on security

What about security? Today's browsers offer users the ability to crank their security levels up, to turn off JavaScript technology, and disable any number of options in their browser. In these cases, your code probably won't work under any circumstances. For these situations, you'll have to handle problems gracefully -- that's at least one article in itself, one I will tackle later (it's going to be a long series, isn't it? Don't worry; you'll master all of this before you're through). For now, you're writing robust, but not perfect, code, which is great for getting a handle on Ajax. You'll come back to the finer details.
Request/Response in an Ajax world

So you now understand Ajax and have a basic idea about the XMLHttpRequest object and how to create it. If you've read closely, you even realize that it's the JavaScript technology that talks to any Web application on the server rather than your HTML form being submitted to that application directly.

What's the missing piece? How to actually use XMLHttpRequest. Since this is critical code that you'll use in some form in every Ajax application you write, take a quick tour through what a basic request/response model with Ajax looks like.

Making a request

You have your shiny new XMLHttpRequest object; now take it for a spin. First, you need a JavaScript method that your Web page can call (like when a user types in text or selects an option from a menu). Then, you'll follow the same basic outline in almost all of your Ajax applications:

Get whatever data you need from the Web form.

Build the URL to connect to.

Open a connection to the server.

Set up a function for the server to run when it's done.

Send the request.

HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code5#code5" Listing 5 is a sample of an Ajax method that does these very things, in this order:Listing 5. Make a request with Ajax



function callServer() {

// Get the city and state from the web form

var city = document.getElementById("city").value;

var state = document.getElementById("state").value;

// Only go on if there are values for both fields

if ((city == null) || (city == "")) return;

if ((state == null) || (state == "")) return;
// Build the URL to connect to

var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);
// Open a connection to the server

xmlHttp.open("GET", url, true);
// Setup a function for the server to run when it's done

xmlHttp.onreadystatechange = updatePage;
// Send the request

xmlHttp.send(null);

}
A lot of this is self-explanatory. The first bit of the code uses basic JavaScript code to grab the values of a few form fields. Then the code sets up a PHP script as the destination to connect to. Notice how the URL of the script is specified and then the city and state (from the form) are appended to this using simple GET parameters.

Next, a connection is opened; here's the first place you see XMLHttpRequest in action again. The method of connection is indicated (GET), as well as the URL to connect to. The final parameter, when set to true, requests an asynchronous connection (thus making this Ajax). If you used false, the code would wait around on the server when the request was made and not continue until a response was received. By setting this to true, your users can still use the form (and even call other JavaScript methods) while the server is processing this request in the background.

The onreadystatechange property of xmlHttp (remember, that's your instance of the XMLHttpRequest object) allows you to tell the server what to do when it does finish running (which could be in five minutes or five hours). Since the code isn't going to wait around for the server, you'll need to let the server know what to do so you can respond to it. In this case, a specific method -- called updatePage() -- will be triggered when the server is finished processing your request.

Finally, send() is called with a value of null. Since you've added the data to send to the server (the city and state) in the request URL, you don't need to send anything in the request. So this fires off your request and the server can do what you asked it to do.

If you don't get anything else out of this, notice how straightforward and simple this is! Other than getting the asynchronous nature of Ajax into your head, this is relatively simple stuff. You'll appreciate how it frees you up to concentrate on cool applications and interfaces rather than complicated HTTP request/response code.

The code in HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code5#code5" Listing 5 is about as easy as it gets. The data is simple text and can be included as part of the request URL. GET sends the request rather than the more complicated POST. There's no XML or content headers to add, no data to send in the body of the request -- this is Ajax Utopia, in other words.

Have no fear; things will become more complicated as this series progresses. You'll learn how to send POST requests, how to set request headers and content types, how to encode XML in your message, how to add security to your request -- the list is pretty long! Don't worry about the hard stuff for now; get your head around the basics, and you'll soon build up a whole arsenal of Ajax tools.

Handling the response

Now you need to actually deal with the server's response. You really only need to know two things at this point:

Don't do anything until the xmlHttp.readyState property is equal to 4.

The server will stuff it's response into the xmlHttp.responseText property.

The first of these -- ready states -- is going to take up the bulk of the next article; you'll learn more about the stages of an HTTP request than you ever wanted to know. For now, if you simply check for a certain value (4), things will work (and you'll have something to look forward to in the next article). The second item -- using the xmlHttp.responseText property to get the server's response -- is easy. HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code6#code6" Listing 6 shows an example of a method that the server can call based on the values sent in HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code5#code5" Listing 5.Listing 6. Handle the server's response



function updatePage() {

if (xmlHttp.readyState == 4) {

var response = xmlHttp.responseText;

document.getElementById("zipCode").value = response;

}

}
Again, this code isn't so difficult or complicated. It waits for the server to call it with the right ready state and then uses the value that the server returns (in this case, the ZIP code for the user-entered city and state) to set the value of another form field. The result is that the zipCode field suddenly appears with the ZIP code -- but the user never had to click a button!. That's the desktop application feel I talked about earlier. Responsiveness, a dynamic feel, and more, all with a little Ajax code.

Observant readers might notice that the zipCode field is a normal text field. Once the server returns the ZIP code and the updatePage() method sets the value of that field with the city/state ZIP code, users can override the value. That's intentional for two reasons: To keep things in the example simple and to show you that sometimes you want users to be able to override what a server says. Keep both in mind; they're important in good user-interface design.
Hooking in the Web form

So what's left? Actually, not much. You have a JavaScript method that grabs information that the user put into a form, sends it to the server, provides another JavaScript method to listen for and handle a response, and even sets the value of a field when that response comes back. All that's really left is to call that first JavaScript method and start the whole process. You could obviously add a button to your HTML form, but that's pretty 2001, don't you think? Take advantage of JavaScript technology like in HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "code7#code7" Listing 7.Listing 7. Kick off an Ajax process





City:
onChange="callServer();" />



State:
onChange="callServer();" />



Zip Code:




If this feels like yet one more piece of fairly routine code, then you're right -- it is! When a user puts in a new value for either the city or state field, the callServer() method fires off and the Ajax fun begins. Starting to feel like you've got a handle on things? Good; that's the idea!
In conclusion

At this point, you're probably not ready to go out and write your first Ajax application -- at least, not unless you're willing to do some real digging in the HYPERLINK "http://www.ibm.com/developerworks/xml/library/wa-ajaxintro1.html?S_TACT=105AGX52&S_CMP=cn-a-x" \l "resources#resources" Resources section. However, you can start to get the basic idea of how these applications work and a basic understanding of the XMLHttpRequest object. In the articles to come, you'll learn to master this object, how to handle JavaScript-to-server communication, how to work with HTML forms, and even get a handle on the DOM.

For now, though, spend some time thinking about just how powerful Ajax applications can be. Imagine a Web form that responds to you not just when you click a button, but when you type into a field, when you select an option from a combo box...even when you drag your mouse around the screen. Think about exactly what asynchronous means; think about JavaScript code running and not waiting on the server to respond to its requests. What sorts of problems can you run into? What areas do you watch out for? And how will the design of your forms change to account for this new approach in programming?

If you spend some real time with these issues, you'll be better served than just having some code you can cut-and-paste and throw into an application that you really don't understand. In the next article, you'll put these ideas into practice and I'll give you the details on the code you need to really make applications like this work. So, until then, enjoy the possibilities of Ajax.Ajax 入门简介

Ajax 由 HTML、JavaScript™ 技术、DHTML 和 DOM 组成,这一杰出的方法可以将笨拙的 Web 界面转化成交互性的 Ajax 应用程序。 HYPERLINK "http://www.ibm.com/developerworks/cn/web/wa-ajaxintro/" 本系列的作者是一位 Ajax 专家,他演示了这些技术如何协同工作 —— 从总体概述到细节的讨论 —— 使高效的 Web 开发成为现实。他还揭开了 Ajax 核心概念的神秘面纱,包括 XMLHttpRequest 对象。

五年前,如果不知道 XML,您就是一只无人重视的丑小鸭。十八个月前,Ruby 成了关注的中心,不知道 Ruby 的程序员只能坐冷板凳了。今天,如果想跟上最新的技术时尚,那您的目标就是 Ajax。

但是,Ajax 不仅仅 是一种时尚,它是一种构建网站的强大方法,而且不像学习一种全新的语言那样困难。

但在详细探讨 Ajax 是什么之前,先让我们花几分钟了解 Ajax 做 什么。目前,编写应用程序时有两种基本的选择:

桌面应用程序

Web 应用程序

两者是类似的,桌面应用程序通常以 CD 为介质(有时候可从网站下载)并完全安装到您的计算机上。桌面应用程序可能使用互联网下载更新,但运行这些应用程序的代码在桌面计算机上。Web 应用程序运行在某处的 Web 服务器上 —— 毫不奇怪,要通过 Web 浏览器访问这种应用程序。

不过,比这些应用程序的运行代码放在何处更重要的是,应用程序如何运转以及如何与其进行交互。桌面应用程序一般很快(就在您的计算机上运行,不用等待互联网连接),具有漂亮的用户界面(通常和操作系统有关)和非凡的动态性。可以单击、选择、输入、打开菜单和子菜单、到处巡游,基本上不需要等待。

另一方面,Web 应用程序是最新的潮流,它们提供了在桌面上不能实现的服务(比如 Amazon.com 和 eBay)。但是,伴随着 Web 的强大而出现的是等待,等待服务器响应,等待屏幕刷新,等待请求返回和生成新的页面。

显然这样说过于简略了,但基本的概念就是如此。您可能已经猜到,Ajax 尝试建立桌面应用程序的功能和交互性,与不断更新的 Web 应用程序之间的桥梁。可以使用像桌面应用程序中常见的动态用户界面和漂亮的控件,不过是在 Web 应用程序中。

还等什么呢?我们来看看 Ajax 如何将笨拙的 Web 界面转化成能迅速响应的 Ajax 应用程序吧。

老技术,新技巧

在谈到 Ajax 时,实际上涉及到多种技术,要灵活地运用它必须深入了解这些不同的技术(本系列的头几篇文章将分别讨论这些技术)。好消息是您可能已经非常熟悉其中的大部分技术,更好的是这些技术都很容易学习,并不像完整的编程语言(如 Java 或 Ruby)那样困难。下面是 Ajax 应用程序所用到的基本技术:

HTML 用于建立 Web 表单并确定应用程序其他部分使用的字段。

1、JavaScript 代码是运行 Ajax 应用程序的核心代码,帮助改进服务器应用程序的通信。

DHTML 或 Dynamic HTML,用于动态更新表单。我们将使用 div、span 和其他动态 HTML 元素来标记 HTML。

文档对象模型 DOM 用于(通过 JavaScript 代码)处理 HTML 结构和(某些情况下)服务器返回的 XML。

我们来进一步分析这些技术的职责。以后的文章中我将深入讨论这些技术,目前只要熟悉这些组件和技术就可以了。对这些代码越熟悉,就越容易从对这些技术的零散了解转变到真正把握这些技术(同时也真正打开了 Web 应用程序开发的大门)。

XMLHttpRequest 对象

要了解的一个对象可能对您来说也是最陌生的,即 XMLHttpRequest。这是一个 JavaScript 对象,创建该对象很简单,如 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code1#code1" 清单 1 所示。清单 1. 创建新的 XMLHttpRequest 对象




下一期文章中将进一步讨论这个对象,现在要知道这是处理所有服务器通信的对象。继续阅读之前,先停下来想一想:通过 XMLHttpRequest 对象与服务器进行对话的是 JavaScript 技术。这不是一般的应用程序流,这恰恰是 Ajax 的强大功能的来源。

在一般的 Web 应用程序中,用户填写表单字段并单击 Submit 按钮。然后整个表单发送到服务器,服务器将它转发给处理表单的脚本(通常是 PHP 或 Java,也可能是 CGI 进程或者类似的东西),脚本执行完成后再发送回全新的页面。该页面可能是带有已经填充某些数据的新表单的 HTML,也可能是确认页面,或者是具有根据原来表单中输入数据选择的某些选项的页面。当然,在服务器上的脚本或程序处理和返回新表单时用户必须等待。屏幕变成一片空白,等到服务器返回数据后再重新绘制。这就是交互性差的原因,用户得不到立即反馈,因此感觉不同于桌面应用程序。

Ajax 基本上就是把 JavaScript 技术和 XMLHttpRequest 对象放在 Web 表单和服务器之间。当用户填写表单时,数据发送给一些 JavaScript 代码而不是 直接发送给服务器。相反,JavaScript 代码捕获表单数据并向服务器发送请求。同时用户屏幕上的表单也不会闪烁、消失或延迟。换句话说,JavaScript 代码在幕后发送请求,用户甚至不知道请求的发出。更好的是,请求是异步发送的,就是说 JavaScript 代码(和用户)不用等待服务器的响应。因此用户可以继续输入数据、滚动屏幕和使用应用程序。

然后,服务器将数据返回 JavaScript 代码(仍然在 Web 表单中),后者决定如何处理这些数据。它可以迅速更新表单数据,让人感觉应用程序是立即完成的,表单没有提交或刷新而用户得到了新数据。JavaScript 代码甚至可以对收到的数据执行某种计算,再发送另一个请求,完全不需要用户干预!这就是 XMLHttpRequest 的强大之处。它可以根据需要自行与服务器进行交互,用户甚至可以完全不知道幕后发生的一切。结果就是类似于桌面应用程序的动态、快速响应、高交互性的体验,但是背后又拥有互联网的全部强大力量。

加入一些 JavaScript

得到 XMLHttpRequest 的句柄后,其他的 JavaScript 代码就非常简单了。事实上,我们将使用 JavaScript 代码完成非常基本的任务:

1、 获取表单数据:JavaScript 代码很容易从 HTML 表单中抽取数据并发送到服务器。

修改表单上的数据:更新表单也很简单,从设置字段值到迅速替换图像。

解析 HTML 和 XML:使用 JavaScript 代码操纵 DOM(请参阅 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "dom#dom" 下一节),处理 HTML 表单服务器返回的 XML 数据的结构。

对于前两点,需要非常熟悉 getElementById() 方法,如 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code2#code2" 清单 2 所示。清单 2. 用 JavaScript 代码捕获和设置字段值



// Get the value of the "phone" field and stuff it in a variable called phone

var phone = document.getElementById("phone").value;

// Set some values on a form using an array called response

document.getElementById("order").value = response[0];

document.getElementById("address").value = response[1];
这里没有特别需要注意的地方,真是好极了!您应该认识到这里并没有非常复杂的东西。只要掌握了 XMLHttpRequest,Ajax 应用程序的其他部分就是如 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code2#code2" 清单 2 所示的简单 JavaScript 代码了,混合有少量的 HTML。同时,还要用一点儿 DOM,我们就来看看吧。

以 DOM 结束

最后还有 DOM,即文档对象模型。可能对有些读者来说 DOM 有点儿令人生畏,HTML 设计者很少使用它,即使 JavaScript 程序员也不大用到它,除非要完成某项高端编程任务。大量使用 DOM 的是 复杂的 Java 和 C/C++ 程序,这可能就是 DOM 被认为难以学习的原因。

幸运的是,在 JavaScript 技术中使用 DOM 很容易,也非常直观。现在,按照常规也许应该说明如何使用 DOM,或者至少要给出一些示例代码,但这样做也可能误导您。即使不理会 DOM,仍然能深入地探讨 Ajax,这也是我准备采用的方法。以后的文章将再次讨论 DOM,现在只要知道可能需要 DOM 就可以了。当需要在 JavaScript 代码和服务器之间传递 XML 和改变 HTML 表单的时候,我们再深入研究 DOM。没有它也能做一些有趣的工作,因此现在就把 DOM 放到一边吧。
获取 Request 对象

有了上面的基础知识后,我们来看看一些具体的例子。XMLHttpRequest 是 Ajax 应用程序的核心,而且对很多读者来说可能还比较陌生,我们就从这里开始吧。从 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code1#code1" 清单 1 可以看出,创建和使用这个对象非常简单,不是吗?等一等。

还记得几年前的那些讨厌的浏览器战争吗?没有一样东西在不同的浏览器上得到同样的结果。不管您是否相信,这些战争仍然在继续,虽然规模较小。但令人奇怪的是,XMLHttpRequest 成了这场战争的牺牲品之一。因此获得 XMLHttpRequest 对象可能需要采用不同的方法。下面我将详细地进行解释。

使用 Microsoft 浏览器

Microsoft 浏览器 Internet Explorer 使用 MSXML 解析器处理 XML(可以通过 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "resources#resources" 参考资料 进一步了解 MSXML)。因此如果编写的 Ajax 应用程序要和 Internet Explorer 打交道,那么必须用一种特殊的方式创建对象。

但并不是这么简单。根据 Internet Explorer 中安装的 JavaScript 技术版本不同,MSXML 实际上有两种不同的版本,因此必须对这两种情况分别编写代码。请参阅 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code3#code3" 清单 3,其中的代码在 Microsoft 浏览器上创建了一个 XMLHttpRequest。清单 3. 在 Microsoft 浏览器上创建 XMLHttpRequest 对象



var xmlHttp = false;

try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e2) {

xmlHttp = false;

}

}
您对这些代码可能还不完全理解,但没有关系。当本系列文章结束的时候,您将对 JavaScript 编程、错误处理、条件编译等有更深的了解。现在只要牢牢记住其中的两行代码:

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");



xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");。

这两行代码基本上就是尝试使用一个版本的 MSXML 创建对象,如果失败则使用另一个版本创建该对象。不错吧?如果都不成功,则将 xmlHttp 变量设为 false,告诉您的代码出现了问题。如果出现这种情况,可能是因为安装了非 Microsoft 浏览器,需要使用不同的代码。

处理 Mozilla 和非 Microsoft 浏览器

如果选择的浏览器不是 Internet Explorer,或者为非 Microsoft 浏览器编写代码,就需要使用不同的代码。事实上就是 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code1#code1" 清单 1 所示的一行简单代码:

var xmlHttp = new XMLHttpRequest object;。

这行简单得多的代码在 Mozilla、Firefox、Safari、Opera 以及基本上所有以任何形式或方式支持 Ajax 的非 Microsoft 浏览器中,创建了 XMLHttpRequest 对象。

结合起来

关键是要支持所有 浏览器。谁愿意编写一个只能用于 Internet Explorer 或者非 Microsoft 浏览器的应用程序呢?或者更糟,要编写一个应用程序两次?当然不!因此代码要同时支持 Internet Explorer 和非 Microsoft 浏览器。 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code4#code4" 清单 4 显示了这样的代码。清单 4. 以支持多种浏览器的方式创建 XMLHttpRequest 对象



/* Create a new XMLHttpRequest object to talk to the Web server */

var xmlHttp = false;

/*@cc_on @*/

/*@if (@_jscript_version >= 5)

try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e2) {

xmlHttp = false;

}

}

@end @*/

if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {

xmlHttp = new XMLHttpRequest();

}
现在先不管那些注释掉的奇怪符号,如 @cc_on,这是特殊的 JavaScript 编译器命令,将在下一期针对 XMLHttpRequest 的文章中详细讨论。这段代码的核心分为三步:

建立一个变量 xmlHttp 来引用即将创建的 XMLHttpRequest 对象。

尝试在 Microsoft 浏览器中创建该对象:

尝试使用 Msxml2.XMLHTTP 对象创建它。

如果失败,再尝试 Microsoft.XMLHTTP 对象。

如果仍然没有建立 xmlHttp,则以非 Microsoft 的方式创建该对象。

最后,xmlHttp 应该引用一个有效的 XMLHttpRequest 对象,无论运行什么样的浏览器。

关于安全性的一点说明

安全性如何呢?现在浏览器允许用户提高他们的安全等级,关闭 JavaScript 技术,禁用浏览器中的任何选项。在这种情况下,代码无论如何都不会工作。此时必须适当地处理问题,这需要单独的一篇文章来讨论,要放到以后了(这个系列够长了吧?不用担心,读完之前也许您就掌握了)。现在要编写一段健壮但不够完美的代码,对于掌握 Ajax 来说就很好了。以后我们还将讨论更多的细节。Ajax 世界中的请求/响应

现在我们介绍了 Ajax,对 XMLHttpRequest 对象以及如何创建它也有了基本的了解。如果阅读得很仔细,您可能已经知道与服务器上的 Web 应用程序打交道的是 JavaScript 技术,而不是直接提交给那个应用程序的 HTML 表单。

还缺少什么呢?到底如何使用 XMLHttpRequest。因为这段代码非常重要,您编写的每个 Ajax 应用程序都要以某种形式使用它,先看看 Ajax 的基本请求/响应模型是什么样吧。

发出请求

您已经有了一个崭新的 XMLHttpRequest 对象,现在让它干点活儿吧。首先需要一个 Web 页面能够调用的 JavaScript 方法(比如当用户输入文本或者从菜单中选择一项时)。接下来就是在所有 Ajax 应用程序中基本都雷同的流程:

从 Web 表单中获取需要的数据。

建立要连接的 URL。

打开到服务器的连接。

设置服务器在完成后要运行的函数。

发送请求。

HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code5#code5" 清单 5 中的示例 Ajax 方法就是按照这个顺序组织的:清单 5. 发出 Ajax 请求



function callServer() {

// Get the city and state from the web form

var city = document.getElementById("city").value;

var state = document.getElementById("state").value;

// Only go on if there are values for both fields

if ((city == null) || (city == "")) return;

if ((state == null) || (state == "")) return;

// Build the URL to connect to

var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);

// Open a connection to the server

xmlHttp.open("GET", url, true);

// Setup a function for the server to run when it's done

xmlHttp.onreadystatechange = updatePage;

// Send the request

xmlHttp.send(null);

}
其中大部分代码意义都很明确。开始的代码使用基本 JavaScript 代码获取几个表单字段的值。然后设置一个 PHP 脚本作为链接的目标。要注意脚本 URL 的指定方式,city 和 state(来自表单)使用简单的 GET 参数附加在 URL 之后。

然后打开一个连接,这是您第一次看到使用 XMLHttpRequest。其中指定了连接方法(GET)和要连接的 URL。最后一个参数如果设为 true,那么将请求一个异步连接(这就是 Ajax 的由来)。如果使用 false,那么代码发出请求后将等待服务器返回的响应。如果设为 true,当服务器在后台处理请求的时候用户仍然可以使用表单(甚至调用其他 JavaScript 方法)。

xmlHttp(要记住,这是 XMLHttpRequest 对象实例)的 onreadystatechange 属性可以告诉服务器在运行完成 后(可能要用五分钟或者五个小时)做什么。因为代码没有等待服务器,必须让服务器知道怎么做以便您能作出响应。在这个示例中,如果服务器处理完了请求,一个特殊的名为 updatePage() 的方法将被触发。

最后,使用值 null 调用 send()。因为已经在请求 URL 中添加了要发送给服务器的数据(city 和 state),所以请求中不需要发送任何数据。这样就发出了请求,服务器按照您的要求工作。

如果没有发现任何新鲜的东西,您应该体会到这是多么简单明了!除了牢牢记住 Ajax 的异步特性外,这些内容都相当简单。应该感激 Ajax 使您能够专心编写漂亮的应用程序和界面,而不用担心复杂的 HTTP 请求/响应代码。

HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code5#code5" 清单 5 中的代码说明了 Ajax 的易用性。数据是简单的文本,可以作为请求 URL 的一部分。用 GET 而不是更复杂的 POST 发送请求。没有 XML 和要添加的内容头部,请求体中没有要发送的数据;换句话说,这就是 Ajax 的乌托邦。

不用担心,随着本系列文章的展开,事情会变得越来越复杂。您将看到如何发送 POST 请求、如何设置请求头部和内容类型、如何在消息中编码 XML、如何增加请求的安全性,可以做的工作还有很多!暂时先不用管那些难点,掌握好基本的东西就行了,很快我们就会建立一整套的 Ajax 工具库。

处理响应

现在要面对服务器的响应了。现在只要知道两点:

1、什么也不要做,直到 xmlHttp.readyState 属性的值等于 4。

2、服务器将把响应填充到 xmlHttp.responseText 属性中。

其中的第一点,即就绪状态,将在下一篇文章中详细讨论,您将进一步了解 HTTP 请求的阶段,可能比您设想的还多。现在只要检查一个特定的值(4)就可以了(下一期文章中还有更多的值要介绍)。第二点,使用 xmlHttp.responseText 属性获得服务器的响应,这很简单。 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code6#code6" 清单 6 中的示例方法可供服务器根据 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code5#code5" 清单 5 中发送的数据调用。清单 6. 处理服务器响应



function updatePage() {

if (xmlHttp.readyState == 4) {

var response = xmlHttp.responseText;

document.getElementById("zipCode").value = response;

}

}
这些代码同样既不难也不复杂。它等待服务器调用,如果是就绪状态,则使用服务器返回的值(这里是用户输入的城市和州的 ZIP 编码)设置另一个表单字段的值。于是包含 ZIP 编码的 zipCode 字段突然出现了,而用户没有按任何按钮!这就是前面所说的桌面应用程序的感觉。快速响应、动态感受等等,这些都只因为有了小小的一段 Ajax 代码。

细心的读者可能注意到 zipCode 是一个普通的文本字段。一旦服务器返回 ZIP 编码,updatePage() 方法就用城市/州的 ZIP 编码设置那个字段的值,用户就可以改写该值。这样做有两个原因:保持例子简单,说明有时候可能希望 用户能够修改服务器返回的数据。要记住这两点,它们对于好的用户界面设计来说很重要。连接 Web 表单

还有什么呢?实际上没有多少了。一个 JavaScript 方法捕捉用户输入表单的信息并将其发送到服务器,另一个 JavaScript 方法监听和处理响应,并在响应返回时设置字段的值。所有这些实际上都依赖于调用 第一个 JavaScript 方法,它启动了整个过程。最明显的办法是在 HTML 表单中增加一个按钮,但这是 2001 年的办法,您不这样认为吗?还是像 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "code7#code7" 清单 7 这样利用 JavaScript 技术吧。清单 7. 启动一个 Ajax 过程





City:
onChange="callServer();" />



State:
onChange="callServer();" />



Zip Code:




如果感觉这像是一段相当普通的代码,那就对了,正是如此!当用户在 city 或 state 字段中输入新的值时,callServer() 方法就被触发,于是 Ajax 开始运行了。有点儿明白怎么回事了吧?好,就是如此!
结束语

现在您可能已经准备开始编写第一个 Ajax 应用程序了,至少也希望认真读一下 HYPERLINK "http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html" \l "resources#resources" 参考资料中的那些文章了吧?但可以首先从这些应用程序如何工作的基本概念开始,对 XMLHttpRequest 对象有基本的了解。在下一期文章中,您将掌握这个对象,学会如何处理 JavaScript 和服务器的通信、如何使用 HTML 表单以及如何获得 DOM 句柄。

现在先花点儿时间考虑考虑 Ajax 应用程序有多么强大。设想一下,当单击按钮、输入一个字段、从组合框中选择一个选项或者用鼠标在屏幕上拖动时,Web 表单能够立刻作出响应会是什么情形。想一想异步 究竟意味着什么,想一想 JavaScript 代码运行而且不等待 服务器对它的请求作出响应。会遇到什么样的问题?会进入什么样的领域?考虑到这种新的方法,编程的时候应如何改变表单的设计?

如果在这些问题上花一点儿时间,与简单地剪切/粘贴某些代码到您根本不理解的应用程序中相比,收益会更多。在下一期文章中,我们将把这些概念付诸实践,详细介绍使应用程序按照这种方式工作所需要的代码。因此,现在先享受一下 Ajax 所带来的可能性吧。

免费下载 ×

下载APP,支持永久资源免费下载

下载APP 免费下载
温馨提示
请用电脑打开本网页,即可以免费获取你想要的了。
扫描加我微信 ×

演示

×
登录 ×


下载 ×
论文助手网
论文助手,最开放的学术期刊平台
				暂无来源信息			 
回复
来来来,吐槽点啥吧

作者联系方式

×

向作者索要->