版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
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對象我們已經(jīng)討論了動態(tài)web應(yīng)用的發(fā)展歷史,并簡要介紹了ajax,下面再來討論問題的關(guān)鍵:如何使用xmlhttprequest對象。盡管與其說ajax是一種技術(shù),不如說是一種技巧,但如果沒有對xmlhttprequest的廣泛支持,google sug
37、gest和ta-da list可能不會像我們看到的有今天這樣的發(fā)展,而你可能也不會看到手上的這本書!xmlhttprequest最早是在ie 5中以activex組件形式實現(xiàn)的。由于只能在ie中使用,所以大多數(shù)開發(fā)人員都沒有用xmlhttprequest,直到最近,mozilla 1.0和safari 1.2把它采用為事實上的標(biāo)準(zhǔn),情況才有改觀。需要重點說明的是,xmlhttprequest并不是一個w3c標(biāo)準(zhǔn),不過許多功能已經(jīng)涵蓋在一個新提案中:dom level 3加載和保存規(guī)約(dom level 3 load and save specification)。因為它不是標(biāo)準(zhǔn),所以在不同瀏
38、覽器上的表現(xiàn)也稍有區(qū)別,不過大多數(shù)方法和屬性都得到了廣泛的支持。當(dāng)前,firefox、safari、opera、konqueror和internet explorer都以類似的方式實現(xiàn)了xmlhttprequest對象的行為。前面已經(jīng)說過,如果大量用戶還是在使用較舊的瀏覽器訪問網(wǎng)站或應(yīng)用,就要三思了。第1章討論過,在這種情況下,如果要使用ajax技術(shù),要么需要開發(fā)一個候選網(wǎng)站,要么你的應(yīng)用應(yīng)當(dāng)能妥善地降級。大多數(shù)使用統(tǒng)計表明,在當(dāng)前使用的瀏覽器中只有極少數(shù)不支持xmlhttprequest,所以一般情況下不會存在這個問題。不過,還是應(yīng)該查看web日志,確定你的用戶在使用什么樣的客戶端來訪問網(wǎng)站
39、。 xmlhttprequest對象概述在使用xmlhttprequest對象發(fā)送請求和處理響應(yīng)之前,必須先用javascript創(chuàng)建一個xmlhttprequest對象。由于xmlhttprequest不是一個w3c標(biāo)準(zhǔn),所以可以采用多種方法使用javascript來創(chuàng)建xmlhttprequest的實例。internet explorer把xmlhttprequest實現(xiàn)為一個activex對象,其他瀏覽器(如firefox、safari和opera)把它實現(xiàn)為一個本地javascript對象。由于存在這些差別,javascript代碼中必須包含有關(guān)的邏輯,從而使用activex技術(shù)或者使
40、用本地javascript對象技術(shù)來創(chuàng)建xmlhttprequest的一個實例。很多人可能還記得從前的那段日子,那時不同瀏覽器上的javascript和dom實現(xiàn)簡直千差萬別,聽了上面這段話之后,這些人可能又會不寒而栗。幸運的是,在這里為了明確該如何創(chuàng)建xmlhttprequest對象的實例,并不需要那么詳細地編寫代碼來區(qū)別瀏覽器類型。你要做的只是檢查瀏覽器是否提供對activex對象的支持。如果瀏覽器支持activex對象,就可以使用activex來創(chuàng)建xmlhttprequest對象。否則,就要使用本地javascript對象技術(shù)來創(chuàng)建。如果window.activexobject調(diào)用失敗
41、(返回null),javascript就會轉(zhuǎn)到else語句分支,確定瀏覽器是否把xmlhttprequest實現(xiàn)為一個本地javascript對象。如果存在window. xmlhttprequest,就會創(chuàng)建xmlhttprequest的一個實例。由于javascript具有動態(tài)類型特性,而且xmlhttprequest在不同瀏覽器上的實現(xiàn)是兼容的,所以可以用同樣的方式訪問xmlhttprequest實例的屬性和方法,而不論這個實例創(chuàng)建的方法是什么。這就大大簡化了開發(fā)過程,而且在javascript中也不必編寫特定于瀏覽器的邏輯。方法和屬性表2-1顯示了xmlhttprequest對象的一些
42、典型方法。不要擔(dān)心,稍后就會詳細介紹這些方法。表2-1標(biāo)準(zhǔn)xmlhttprequest操作方 法描 述abort()停止當(dāng)前請求getallresponseheaders()把http請求的所有響應(yīng)首部作為鍵/值對返回getresponseheader(header)返回指定首部的串值open(method, url)建立對服務(wù)器的調(diào)用。method參數(shù)可以是get、post或put。url參數(shù)可以是相對url或絕對url。這個方法還包括3個可選的參數(shù)send(content)向服務(wù)器發(fā)送請求setrequestheader(header, value)把指定首部設(shè)置為所提供的值。在設(shè)置任何首
43、部之前必須先調(diào)用open()下面來更詳細地討論這些方法。void open(string method, string url, boolean asynch, string username, string password):這個方法會建立對服務(wù)器的調(diào)用。這是初始化一個請求的純腳本方法。它有兩個必要的參數(shù),還有3個可選參數(shù)。要提供調(diào)用的特定方法(get、post或put),還要提供所調(diào)用資源的url。另外還可以傳遞一個boolean值,指示這個調(diào)用是異步的還是同步的。默認值為true,表示請求本質(zhì)上是異步的。如果這個參數(shù)為false,處理就會等待,直到從服務(wù)器返回響應(yīng)為止。由于異步調(diào)用是使
44、用ajax的主要優(yōu)勢之一,所以倘若將這個參數(shù)設(shè)置為false,從某種程度上講與使用xmlhttprequest對象的初衷不太相符。不過,前面已經(jīng)說過,在某些情況下這個參數(shù)設(shè)置為false也是有用的,比如在持久存儲頁面之前可以先驗證用戶的輸入。最后兩個參數(shù)不說自明,允許你指定一個特定的用戶名和密碼。void send(content):這個方法具體向服務(wù)器發(fā)出請求。如果請求聲明為異步的,這個方法就會立即返回,否則它會等待直到接收到響應(yīng)為止??蛇x參數(shù)可以是dom對象的實例、輸入流,或者串。傳入這個方法的內(nèi)容會作為請求體的一部分發(fā)送。void setrequestheader(string head
45、er, string value):這個方法為http請求中一個給定的首部設(shè)置值。它有兩個參數(shù),第一個串表示要設(shè)置的首部,第二個串表示要在首部中放置的值。需要說明,這個方法必須在調(diào)用open()之后才能調(diào)用。在所有這些方法中,最有可能用到的就是open()和send()。xmlhttprequest對象還有許多屬性,在設(shè)計ajax交互時這些屬性非常有用。void abort():顧名思義,這個方法就是要停止請求。string getallresponseheaders():這個方法的核心功能對web應(yīng)用開發(fā)人員應(yīng)該很熟悉了,它返回一個串,其中包含http請求的所有響應(yīng)首部,首部包括conten
46、t-length、date和uri。string getresponseheader(string header):這個方法與getallresponseheaders()是對應(yīng)的,不過它有一個參數(shù)表示你希望得到的指定首部值,并且把這個值作為串返回。除了這些標(biāo)準(zhǔn)方法,xmlhttprequest對象還提供了許多屬性,如表2-2所示。處理xmlhttprequest時可以大量使用這些屬性。表2-2標(biāo)準(zhǔn)xmlhttprequest屬性屬 性描 述onreadystatechange每個狀態(tài)改變時都會觸發(fā)這個事件處理器,通常會調(diào)用一個javascript函數(shù)readystate請求的狀態(tài)。有5個可取
47、值:0 = 未初始化,1 = 正在加載,2 = 已加載,3 = 交互中,4 = 完成responsetext服務(wù)器的響應(yīng),表示為一個串responsexml服務(wù)器的響應(yīng),表示為xml。這個對象可以解析為一個dom對象status服務(wù)器的http狀態(tài)碼(200對應(yīng)ok,404對應(yīng)not found(未找到),等等)statustexthttp狀態(tài)碼的相應(yīng)文本(ok或not found(未找到)等等) 交互示例看到這里,你可能想知道典型的ajax交互是什么樣。圖2-1顯示了ajax應(yīng)用中標(biāo)準(zhǔn)的交互模式。不同于標(biāo)準(zhǔn)web客戶中所用的標(biāo)準(zhǔn)請求/響應(yīng)方法,ajax應(yīng)用的做法稍有差別。1. 一個客戶端事件
48、觸發(fā)一個ajax事件。從簡單的onchange事件到某個特定的用戶動作,很多這樣的事件都可以觸發(fā)ajax事件??梢杂腥缦碌拇a:客戶服務(wù)器數(shù)據(jù)庫事件服務(wù)器資源使用ajax的web應(yīng)用web容器圖2-1標(biāo)準(zhǔn)ajax交互2. 創(chuàng)建xmlhttprequest對象的一個實例。使用open()方法建立調(diào)用,并設(shè)置url以及所希望的http方法(通常是get或post)。請求實際上通過一個send()方法調(diào)用觸發(fā)。3. 向服務(wù)器做出請求??赡苷{(diào)用servlet、cgi腳本,或者任何服務(wù)器端技術(shù)。4. 服務(wù)器可以做你想做的事情,包括訪問數(shù)據(jù)庫,甚至訪問另一個系統(tǒng)。5.請求返回到瀏覽器。content-ty
49、pe設(shè)置為text/xmlxmlhttprequest對象只能處理text/html類型的結(jié)果。在另外一些更復(fù)雜示例中,響應(yīng)可能涉及更廣,還包括javascript、dom管理以及其他相關(guān)的技術(shù)。需要說明,你還需要設(shè)置另外一些首部,使瀏覽器不會在本地緩存結(jié)果。為此可以使用下面的代碼:response.setheader(cache-control, no-cache);response.setheader(pragma, no-cache);通常,web上提供的各種框架和工具包負責(zé)基本的連接和瀏覽器抽象,有些還增加了用戶界面組件。有一些純粹基于客戶,還有一些需要在服務(wù)器上工作。這些框架中的很多只是剛開始開發(fā),或者還處于發(fā)布的早期階段,隨著新的庫和新的版本的定期出現(xiàn),情況還在不斷發(fā)生變化。這個領(lǐng)域正在日漸成熟,最具優(yōu)勢的將脫穎而出。一些比較成熟的庫包括libxmlrequest、rslite、sarissa、javascript對象注解(javascript object notation,json)、
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度二零二五年度競業(yè)禁止及保密協(xié)議糾紛處理規(guī)定
- 安徽會考文科數(shù)學(xué)試卷
- 二零二五年度知識產(chǎn)權(quán)共享與人才培養(yǎng)合同
- 2025年度汽車4S店專用門窗安裝合同
- 漳州槽底除砂施工方案
- 酉陽木紋鋁單板施工方案
- 二零二五年度家庭專業(yè)護理服務(wù)雇傭協(xié)議
- 2025年度租賃房產(chǎn)租賃合同續(xù)簽流程圖片范本
- 2025年度城市亮化工程電工安全維護協(xié)議
- 二零二五年度退休研究員聘用協(xié)議-科研機構(gòu)技術(shù)交流合作
- 2024年山東省泰安市高考物理一模試卷(含詳細答案解析)
- 腫瘤患者管理
- 2025春夏運動戶外行業(yè)趨勢白皮書
- 《法制宣傳之盜竊罪》課件
- 通信工程單位勞動合同
- 2024年醫(yī)療器械經(jīng)營質(zhì)量管理規(guī)范培訓(xùn)課件
- 2024年計算機二級WPS考試題庫380題(含答案)
- 高低壓配電柜產(chǎn)品營銷計劃書
- 2024年4月自考02202傳感器與檢測技術(shù)試題
- 新入職員工培訓(xùn)考試附有答案
- 外觀質(zhì)量評定報告
評論
0/150
提交評論