网页设计外文翻译使用XMLHttpRequest对象.doc

上传人:仙人指路1688 文档编号:2881241 上传时间:2023-03-01 格式:DOC 页数:13 大小:141.50KB
返回 下载 相关 举报
网页设计外文翻译使用XMLHttpRequest对象.doc_第1页
第1页 / 共13页
网页设计外文翻译使用XMLHttpRequest对象.doc_第2页
第2页 / 共13页
网页设计外文翻译使用XMLHttpRequest对象.doc_第3页
第3页 / 共13页
网页设计外文翻译使用XMLHttpRequest对象.doc_第4页
第4页 / 共13页
网页设计外文翻译使用XMLHttpRequest对象.doc_第5页
第5页 / 共13页
点击查看更多>>
资源描述

《网页设计外文翻译使用XMLHttpRequest对象.doc》由会员分享,可在线阅读,更多相关《网页设计外文翻译使用XMLHttpRequest对象.doc(13页珍藏版)》请在三一办公上搜索。

1、Using the XMLHttpRequest ObjectNow that weve discussed the history of dynamic Web applications and introduced Ajax, its time to cover the heart of the matter: how to use the XMLHttpRequest object. While Ajax is more of a technique than a technology, without widespread support for XMLHttpRequest, Goo

2、gle Suggest and Ta-da List wouldnt exist as we currently know them. And you wouldnt be reading this book! XMLHttpRequest was originally implemented in Internet Explorer 5 as an ActiveX component. That it worked only in Internet Explorer kept most developers from using XMLHttpRequest until its recent

3、 adoption as a de facto standard in Mozilla 1.0 and Safari 1.2. Its important to note that XMLHttpRequest is not a W3C standard, though much of the functionality is covered in a new proposal: the DOM Level 3 Load and Save Specification. Because it is not a standard, its behavior may differ slightly

4、from browser to browser, though most methods and properties are widely supported. Currently, Firefox, Safari, Opera, Konqueror, and Internet Explorer all implement the behavior of the XMLHttpRequest object similarly. That said, if a significant number of your users still access your site or applicat

5、ion with older browsers, you will need to consider your options. As we discussed in Chapter 1, if you are going to use Ajax techniques, you need to either develop an alternative site or allow your application to degrade gracefully. With most usage statistics indicating that only a small fraction of

6、browsers in use today lack XMLHttpRequest support, the chances of this being a problem are slim. However, you need to check your Web logs and determine what clients your customers are using to access your sites. Overview of the XMLHttpRequest Object You must first create an XMLHttpRequest object usi

7、ng JavaScript before you can use the object to send requests and process responses. Since XMLHttpRequest is not a W3C standard, you can use JavaScript in a couple of ways to create an instance of XMLHttpRequest. Internet Explorer implements XMLHttpRequest as an ActiveX object, and other browsers suc

8、h as Firefox, Safari, and Opera implement it as a native JavaScript object. Because of these differences, the JavaScript code must contain logic to create an instance of XMLHttpRequest using the ActiveX technique or using the native JavaScript object technique. The previous statement might send shiv

9、ers down the spines of those who remember the days when the implementation of JavaScript and the DOM varied widely among browsers. Fortunately, in this case you dont need elaborate code to identify the browser type to know how to create an instance of the XMLHttpRequest object. All you need to do is

10、 check the browsers support of ActiveX objects. If the browser supports ActiveX objects, then you create the XMLHttpRequest object using ActiveX. Otherwise, you create it using the native JavaScript object technique. If the call to window.ActiveXObjectfails, then the JavaScript branches to the elses

11、tatement, which determines whether the browser implements XMLHttpRequest as a native JavaScript object. If window.XMLHttpRequestexists, then an instance of XMLHttpRequest is created. Thanks to JavaScripts dynamically typed nature and that XMLHttpRequest implementations are compatible across various

12、browsers, you can access the properties and methods of an instance of XMLHttpRequest identically, regardless of the method used to create the instance. This greatly simplifies the development process and keeps the JavaScript free of browser-specific logic. Methods and Properties Table 2-1 shows some

13、 typical methods on the XMLHttpRequest object. Dont worry; well talk about these methods in greater detail in a moment. Table 2-1. Standard XMLHttpRequest OperationsMethodDescriptionabort()The current request.getAllResponseHeaders()Returns all the response headers for the HTTP request as key/value p

14、airs.getResponseHeader(header)Returns the string value of the specified header.open(method, url)Sets the stage for a call to the server. The method argument can be either GET, POST, or PUT. The url argument can be relative or absolute. This method includes three optional arguments. send(content)Send

15、s the request to the server.setRequestHeader(header, value)Sets the specified header to the supplied value. open() must be called before attempting to set any headers.Lets take a closer look at these methods. void open(string method, string url, boolean asynch, string username, string password): Thi

16、s method sets up your call to the server. This method is meant to be the script-only method of initializing a request. It has two required arguments and three optional arguments. You are required to supply the specific method you are invoking (GET, POST, or PUT) and the URL of the resource you are c

17、alling. You may optionally pass a Boolean indicating whether this call is meant to be asynchronousthe default is true, which means the request is asynchronous in nature. If you pass a false, processing waits until the response returns from the server. Since making calls asynchronously is one of the

18、main benefits of using Ajax, setting this parameter to false somewhat defeats the purpose of using the XMLHttpRequest object. That said, you may find it useful in certain circumstances such as validating user input before allowing the page to be persisted. The last two parameters are self-explanator

19、y, allowing you to include a specific username and password. void send(content): This method actually makes the request to the server. If the request was declared as asynchronous, this method returns immediately, otherwise it waits until the response is received. The optional argument can be an inst

20、ance of a DOM object, an input stream, or a string. The content passed to this method is sent as part of the request body. void setRequestHeader(string header, string value): This method sets a value for a given header value in the HTTP request. It takes a string representing the header to set and a

21、 string representing the value to place in the header. Note that it must be called after a call to open(). Of all these methods, the two you will use the most are open() and send(). The XMLHttpRequest object has a number of properties that prove themselves quite useful while designing Ajax interacti

22、ons. void abort(): This method is really quite self-explanatoryit stops the request.string getAllResponseHeaders(): The core functionality of this method should be familiar to Web application developersit returns a string containing response headers from the HTTP request. Headers include Content-Len

23、gth, Date, and URI.string getResponseHeader(string header): This method is a companion to getAllResponseHeaders() except it takes an argument representing the specific header value you want, returning this value as a string. In addition to these standard methods, the XMLHttpRequest object exposes th

24、e properties listed in Table 2-2. Youll use these properties extensively when working with XMLHttpRequest. Table 2-2. Standard XMLHttpRequest Properties PropertyDescriptiononreadystatechangeThe event handler that fires at every state change, typically a call to a JavaScript function.readyStateThe st

25、ate of the request. The five possible values are 0 = uninitialized, 1 = loading, 2 = loaded, 3 = interactive, and 4 = complete. responseTextThe response from the server as a string.responseXMLThe response from the server as a string. The response from the server as XML. This object can be parsed and

26、 examined as a DOM object.statusThe HTTP status code from the server (that is, 200 for OK, 404 for Not Found, and so on).statusTextThe text version of the HTTP status code (that is, OK or Not Found, and so on).An Example Interaction At this point, you might be wondering what a typical Ajax interacti

27、on looks like. Figure 2-1 Server sourceeventDatabaseWeb ContainerAjax-Enabled Web ApplicationClientServerFigure 2-1. Standard Ajax interactionUnlike the standard request/response approach found in a standard Web client, an Ajax application does things a little bit differently. 1. A client-side event

28、 triggers an Ajax event. Any number of things can trigger this, from a simple onchange event to some specific user action. You might have code like this: 2. An instance of the XMLHttpRequest object is created. Using the open() method, the call is set upthe URL is set along with the desired HTTP meth

29、od, typically GETor POST. The request is actually triggered via a call to the send() method. 3. A request is made to the server. This might be a call to a servlet, a CGI script, or any server-side technique. 4. The server can do anything you can think of, including accessing a data store or even ano

30、ther system. 5. The request is returned to the browser. The Content-Typeis set to text/xmlthe XMLHttpRequest object can process results only of the text/html type. In more complex instances, the response might be quite involved and include JavaScript, DOM manipulation, or other related technologies.

31、 Note that you also need to set the headers so that the browser will not cache the results locally. You do this with the following code: response.setHeader(Cache-Control, no-cache);response.setHeader(Pragma, no-cache); In general, the various frameworks and toolkits available on the Web take care of

32、 the basic wiring and the browser abstractions, and some add user interface components. Some are purely client based; others require work on the server. Many of these frameworks have just begun development or are in the early phases of release; the landscape is constantly changing, with new librarie

33、s and versions coming out regularly. As the field matures, the best ones will become apparent. Some of the more mature libraries include libXmlRequest, RSLite, sarissa,JavaScript Object Notation (JSON), JSRS, Direct Web Remoting (DWR), and Ruby on Rails. This is a dynamic space, so keep your RSS agg

34、regator tuned to those sites dedicated to posting about all things Ajax! Summary While Ajaxesque techniques have been used for many years, the recent adoption of the XMLHttpRequest object by modern browsers has ushered in a new era of developing rich Web applications. In this chapter, we established

35、 the basics of working with the heart of Ajax, the XMLHttpRequest object. At this point, you know the methods and properties of the XMLHttpRequest object, and weve shown you some simple examples of their use. As you can see, the object is pretty straightforward and hides much of its complexity from

36、you. Combined with a healthy dose of JavaScript and some basic DOM manipulation, Ajax allows for a level of interactivity previously unmatched on the Web.英文翻译使用XMLHttpRequest对象我们已经讨论了动态Web应用的发展历史,并简要介绍了Ajax,下面再来讨论问题的关键:如何使用XMLHttpRequest对象。尽管与其说Ajax是一种技术,不如说是一种技巧,但如果没有对XMLHttpRequest的广泛支持,Google Sug

37、gest和Ta-da List可能不会像我们看到的有今天这样的发展,而你可能也不会看到手上的这本书!XMLHttpRequest最早是在IE 5中以ActiveX组件形式实现的。由于只能在IE中使用,所以大多数开发人员都没有用XMLHttpRequest,直到最近,Mozilla 1.0和Safari 1.2把它采用为事实上的标准,情况才有改观。需要重点说明的是,XMLHttpRequest并不是一个W3C标准,不过许多功能已经涵盖在一个新提案中:DOM Level 3加载和保存规约(DOM Level 3 Load and Save Specification)。因为它不是标准,所以在不同浏

38、览器上的表现也稍有区别,不过大多数方法和属性都得到了广泛的支持。当前,Firefox、Safari、Opera、Konqueror和Internet Explorer都以类似的方式实现了XMLHttpRequest对象的行为。前面已经说过,如果大量用户还是在使用较旧的浏览器访问网站或应用,就要三思了。第1章讨论过,在这种情况下,如果要使用Ajax技术,要么需要开发一个候选网站,要么你的应用应当能妥善地降级。大多数使用统计表明,在当前使用的浏览器中只有极少数不支持XMLHttpRequest,所以一般情况下不会存在这个问题。不过,还是应该查看Web日志,确定你的用户在使用什么样的客户端来访问网站

39、。 XMLHttpRequest对象概述在使用XMLHttpRequest对象发送请求和处理响应之前,必须先用JavaScript创建一个XMLHttpRequest对象。由于XMLHttpRequest不是一个W3C标准,所以可以采用多种方法使用JavaScript来创建XMLHttpRequest的实例。Internet Explorer把XMLHttpRequest实现为一个ActiveX对象,其他浏览器(如Firefox、Safari和Opera)把它实现为一个本地JavaScript对象。由于存在这些差别,JavaScript代码中必须包含有关的逻辑,从而使用ActiveX技术或者使

40、用本地JavaScript对象技术来创建XMLHttpRequest的一个实例。很多人可能还记得从前的那段日子,那时不同浏览器上的JavaScript和DOM实现简直千差万别,听了上面这段话之后,这些人可能又会不寒而栗。幸运的是,在这里为了明确该如何创建XMLHttpRequest对象的实例,并不需要那么详细地编写代码来区别浏览器类型。你要做的只是检查浏览器是否提供对ActiveX对象的支持。如果浏览器支持ActiveX对象,就可以使用ActiveX来创建XMLHttpRequest对象。否则,就要使用本地JavaScript对象技术来创建。如果window.ActiveXObject调用失败

41、(返回null),JavaScript就会转到else语句分支,确定浏览器是否把XMLHttpRequest实现为一个本地JavaScript对象。如果存在window. XMLHttpRequest,就会创建XMLHttpRequest的一个实例。由于JavaScript具有动态类型特性,而且XMLHttpRequest在不同浏览器上的实现是兼容的,所以可以用同样的方式访问XMLHttpRequest实例的属性和方法,而不论这个实例创建的方法是什么。这就大大简化了开发过程,而且在JavaScript中也不必编写特定于浏览器的逻辑。方法和属性表2-1显示了XMLHttpRequest对象的一些

42、典型方法。不要担心,稍后就会详细介绍这些方法。表2-1标准XMLHttpRequest操作方 法描 述abort()停止当前请求getAllResponseHeaders()把HTTP请求的所有响应首部作为键/值对返回getResponseHeader(header)返回指定首部的串值open(method, url)建立对服务器的调用。method参数可以是GET、POST或PUT。url参数可以是相对URL或绝对URL。这个方法还包括3个可选的参数send(content)向服务器发送请求setRequestHeader(header, value)把指定首部设置为所提供的值。在设置任何首

43、部之前必须先调用open()下面来更详细地讨论这些方法。void open(string method, string url, boolean asynch, string username, string password):这个方法会建立对服务器的调用。这是初始化一个请求的纯脚本方法。它有两个必要的参数,还有3个可选参数。要提供调用的特定方法(GET、POST或PUT),还要提供所调用资源的URL。另外还可以传递一个Boolean值,指示这个调用是异步的还是同步的。默认值为true,表示请求本质上是异步的。如果这个参数为false,处理就会等待,直到从服务器返回响应为止。由于异步调用是使

44、用Ajax的主要优势之一,所以倘若将这个参数设置为false,从某种程度上讲与使用XMLHttpRequest对象的初衷不太相符。不过,前面已经说过,在某些情况下这个参数设置为false也是有用的,比如在持久存储页面之前可以先验证用户的输入。最后两个参数不说自明,允许你指定一个特定的用户名和密码。void send(content):这个方法具体向服务器发出请求。如果请求声明为异步的,这个方法就会立即返回,否则它会等待直到接收到响应为止。可选参数可以是DOM对象的实例、输入流,或者串。传入这个方法的内容会作为请求体的一部分发送。void setRequestHeader(string head

45、er, string value):这个方法为HTTP请求中一个给定的首部设置值。它有两个参数,第一个串表示要设置的首部,第二个串表示要在首部中放置的值。需要说明,这个方法必须在调用open()之后才能调用。在所有这些方法中,最有可能用到的就是open()和send()。XMLHttpRequest对象还有许多属性,在设计Ajax交互时这些属性非常有用。void abort():顾名思义,这个方法就是要停止请求。string getAllResponseHeaders():这个方法的核心功能对Web应用开发人员应该很熟悉了,它返回一个串,其中包含HTTP请求的所有响应首部,首部包括Conten

46、t-Length、Date和URI。string getResponseHeader(string header):这个方法与getAllResponseHeaders()是对应的,不过它有一个参数表示你希望得到的指定首部值,并且把这个值作为串返回。除了这些标准方法,XMLHttpRequest对象还提供了许多属性,如表2-2所示。处理XMLHttpRequest时可以大量使用这些属性。表2-2标准XMLHttpRequest属性属 性描 述onreadystatechange每个状态改变时都会触发这个事件处理器,通常会调用一个JavaScript函数readyState请求的状态。有5个可取

47、值:0 = 未初始化,1 = 正在加载,2 = 已加载,3 = 交互中,4 = 完成responseText服务器的响应,表示为一个串responseXML服务器的响应,表示为XML。这个对象可以解析为一个DOM对象status服务器的HTTP状态码(200对应OK,404对应Not Found(未找到),等等)statusTextHTTP状态码的相应文本(OK或Not Found(未找到)等等) 交互示例看到这里,你可能想知道典型的Ajax交互是什么样。图2-1显示了Ajax应用中标准的交互模式。不同于标准Web客户中所用的标准请求/响应方法,Ajax应用的做法稍有差别。1. 一个客户端事件

48、触发一个Ajax事件。从简单的onchange事件到某个特定的用户动作,很多这样的事件都可以触发Ajax事件。可以有如下的代码:客户服务器数据库事件服务器资源使用Ajax的Web应用Web容器图2-1标准Ajax交互2. 创建XMLHttpRequest对象的一个实例。使用open()方法建立调用,并设置URL以及所希望的HTTP方法(通常是GET或POST)。请求实际上通过一个send()方法调用触发。3. 向服务器做出请求。可能调用servlet、CGI脚本,或者任何服务器端技术。4. 服务器可以做你想做的事情,包括访问数据库,甚至访问另一个系统。5.请求返回到浏览器。Content-Type设置为text/xmlXMLHttpRequest对象只能处理text/html类型的结果。在另外一些更复杂示例中,响应可能涉及更广,还包括JavaScript、DOM管理以及其他相关的技

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 建筑/施工/环境 > 项目建议


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号