本文將展示一個(gè)開源javascript庫,該腳本庫給AJAX應(yīng)用程序帶來了書簽和后退按鈕支持。在學(xué)習(xí)完這個(gè)教程后,開發(fā)人員將能夠獲得對一個(gè)AJAX問題的解決方案(甚至連Google Maps和Gmail現(xiàn)在都不提供該解決方案):一個(gè)強(qiáng)大的、可用的書簽和后退前進(jìn)功能,其操作行為如同其他的Web應(yīng)用程序一樣。
本文將闡述目前AJAX應(yīng)用程序在使用書簽和后退按鈕方面所面臨的嚴(yán)重問題;展示Really Simple History(RSH)庫――一個(gè)可以解決以上問題的開源框架,并提供幾個(gè)運(yùn)行中的例子。
本文所展示的這個(gè)框架的主要發(fā)明分為兩部分。首先是一個(gè)隱藏的HTML表單,用于緩存大量短期會話的客戶端信息;這種緩存功能為頁面導(dǎo)航提供了強(qiáng)大的支持。其次是超鏈接錨點(diǎn)和隱藏Iframe的組合,它們被嵌入后退和前進(jìn)按鈕,用來截獲和記錄瀏覽器的歷史記錄事件。以上兩種技術(shù)都被包裝在一個(gè)簡單的javascript庫中來簡化開發(fā)。
問題
書簽和后退按鈕在傳統(tǒng)的多頁面Web應(yīng)用程序中運(yùn)行得非常好。當(dāng)用戶瀏覽web站點(diǎn)的時(shí)候,其瀏覽器的地址欄記錄隨新的URL而更新,這些記錄可以被粘貼到電子郵件或者書簽中供以后使用。后退和前進(jìn)按鈕也可以正常操作,使用戶可以在訪問過的頁面中向前或向后翻動。
但是AJAX應(yīng)用程序卻不一樣,它們是運(yùn)行在單個(gè)Web頁面中的復(fù)雜程序。瀏覽器并不是為這類程序而構(gòu)建的――這類Web應(yīng)用程序已經(jīng)過時(shí),它們在每次鼠標(biāo)點(diǎn)擊的時(shí)候都需要重新刷新整個(gè)頁面。
在這種類似于Gmail的AJAX軟件中,瀏覽器的地址欄在用戶選擇功能和改變程序狀態(tài)的時(shí)候保持不變,這使得無法在特定的應(yīng)用程序視圖中使用書簽。此外,如果用戶按下“后退”按鈕來“撤銷”上次的操作,他們會驚奇地發(fā)現(xiàn),瀏覽器會完全離開該應(yīng)用程序的Web頁面。
解決方案
開源RSH框架可以解決這些問題,它為AJAX應(yīng)用程序提供了書簽和控制后退、前進(jìn)按鈕的功能。RSH目前還處于Beta階段,可以在Firefox 1.0、Netscape 7 、Internet Explorer 6 等瀏覽器上運(yùn)行;目前還不支持Safari。
目前有幾個(gè)AJAX框架對書簽和歷史記錄問題有所幫助;但這些框架目前都有幾個(gè)由于實(shí)現(xiàn)而造成的重大Bug。此外,很多AJAX歷史記錄框架被綁定到較大的庫上,例如Backbase和Dojo;這些框架為AJAX應(yīng)用程序引入了完全不同的編程模型,迫使開發(fā)人員使用全新的方式來獲得歷史記錄功能。
相較之下,RSH是一個(gè)可以包含在現(xiàn)有AJAX系統(tǒng)中的簡單模塊。此外,RSH庫采用了一些技術(shù)以避免產(chǎn)生影響其他歷史記錄框架的Bug。
RSH框架由兩個(gè)javascript類組成:DhtmlHistory和HistoryStorage。
DhtmlHistory類為AJAX應(yīng)用程序提供歷史記錄抽象。AJAX頁面使用add()方法添加歷史記錄事件到瀏覽器,指定新的地址和相關(guān)的歷史記錄數(shù)據(jù)。DhtmlHistory類使用一個(gè)錨散列(如#new-location)更新瀏覽器當(dāng)前的URL,同時(shí)把歷史記錄數(shù)據(jù)和該新URL關(guān)聯(lián)。AJAX應(yīng)用程序?qū)⒆约鹤詾闅v史記錄的監(jiān)聽器,當(dāng)用戶使用后退和前進(jìn)按鈕進(jìn)行瀏覽時(shí),歷史記錄事件被觸發(fā),為瀏覽器提供新的位置以及與add()調(diào)用一起保存的任何歷史記錄數(shù)據(jù)。
第二個(gè)類:HistoryStorage,允許開發(fā)人員保存任意數(shù)量的已存歷史記錄數(shù)據(jù)。在普通Web頁面中,當(dāng)用戶導(dǎo)航到一個(gè)新的web站點(diǎn)時(shí),瀏覽器卸載并清除web頁面上的所有應(yīng)用程序和javascript狀態(tài);如果用戶用后退按鈕返回,所有的數(shù)據(jù)都丟失了。HistoryStorage類通過一個(gè)包含簡單散列表方法(例如put()、get()、hasKey())的API來解決這類問題。上面的方法允許開發(fā)人員在用戶離開Web頁面之后保存任意數(shù)量的數(shù)據(jù);當(dāng)用戶按后退按鈕重新返回時(shí),歷史記錄數(shù)據(jù)可以通過HistoryStorage類來訪問。在內(nèi)部,我們通過使用隱藏的表單字段來實(shí)現(xiàn)此功能,這是因?yàn)闉g覽器會自動保存表單字段中的值,甚至在用戶離開Web頁面的時(shí)候也如此。
例子
讓我們先從一個(gè)簡單的例子開始。
首先,任何需要使用RSH框架的頁面都必須包含dhtmlHistory.js腳本:
<!-- Load the Really Simple
History framework -->
<script type="text/javascript"
src="../../framework/dhtmlHistory.js">
</script>
DHTML歷史記錄應(yīng)用程序也必須在與AJAX Web頁面相同的目錄下包含blank.html文件;這個(gè)文件與RSH框架打包在一起,且對于Internet Explorer來說是必需的。順便提一下,RSH使用一個(gè)隱藏Iframe來跟蹤和添加Internet Explorer的歷史記錄變化;這個(gè)Iframe需要我們指定一個(gè)實(shí)際的文件位置才能正常工作,這就是blank.html。
RSH框架創(chuàng)建了一個(gè)叫做dhtmlHistory的全局對象,這是操縱瀏覽器歷史記錄的入口點(diǎn)。使用dhtmlHistory的第一步是在Web頁面加載完成后初始化dhtmlHistory對象:
window.onload = initialize;
function initialize() {
// initialize the DHTML History
// framework
dhtmlHistory.initialize();
然后,開發(fā)人員使用dhtmlHistory.addListener()方法訂閱歷史記錄變化事件。這個(gè)方法帶有一個(gè)javascript回調(diào)函數(shù),當(dāng)DHTML歷史記錄變化事件發(fā)生時(shí),該函數(shù)接收兩個(gè)參數(shù):新的頁面位置以及任何可與該事件關(guān)聯(lián)的可選歷史記錄數(shù)據(jù):
window.onload = initialize;
function initialize() {
// initialize the DHTML History
// framework
dhtmlHistory.initialize();
// subscribe to DHTML history change
// events
dhtmlHistory.addListener(historyChange);
historyChange()方法很簡單,該函數(shù)在用戶導(dǎo)航到一個(gè)新位置后接收newLocation以及任何與該事件關(guān)聯(lián)的可選historyData。
/** Our callback to receive history change
events. */
function historyChange(newLocation,
historyData) {
debug("A history change has occurred: "
"newLocation=" newLocation
", historyData=" historyData,
true);
}
上面用到的debug()方法是定義在示例源文件中的一個(gè)實(shí)用函數(shù),它與完整示例打包在一起供下載。debug()只是用來將消息打印到Web頁面上;第二個(gè)布爾型參數(shù)(在上述代碼中值為true)控制是否在打印新的調(diào)試消息之前清除原有的全部消息。
開發(fā)人員使用add()方法添加歷史記錄事件。添加歷史記錄事件涉及為歷史記錄變化指定一個(gè)新地址,例如edit:SomePage,以及提供一個(gè)和該事件一起保存的可選historyData值。
window.onload = initialize;
function initialize() {
// initialize the DHTML History
// framework
dhtmlHistory.initialize();
// subscribe to DHTML history change
// events
dhtmlHistory.addListener(historyChange);
// if this is the first time we have
// loaded the page...
if (dhtmlHistory.isFirstLoad()) {
debug("Adding values to browser " "history", false);
// start adding history
dhtmlHistory.add("helloworld", "Hello World Data");
dhtmlHistory.add("foobar", 33);
dhtmlHistory.add("boobah", true);
var complexObject = new Object();
complexObject.value1 = "This is the first value";
complexObject.value2 = "This is the second data";
complexObject.value3 = new Array();
complexObject.value3[0] = "array 1";
complexObject.value3[1] = "array 2";
dhtmlHistory.add("complexObject", complexObject);
在add()被調(diào)用之后,新的地址將立即作為一個(gè)錨值(鏈接地址)顯示在瀏覽器的URL地址欄中。例如,對地址為http://codinginparadise.org/my_ajax_app的AJAX Web頁面調(diào)用dhtmlHistory.add("helloworld", "Hello World Data")之后,用戶將會在其瀏覽器URL地址欄中看到如下的地址:
http://codinginparadise.org/my_ajax_app#helloworld
然后用戶可以將這個(gè)頁面做成書簽,如果以后用到這個(gè)書簽,AJAX應(yīng)用程序可以讀取#helloworld值,并用它來初始化Web頁面。散列后面的地址值是RSH框架可以透明編碼和解碼的URL地址。
HistoryData非常有用,它保存比簡單的URL更為復(fù)雜的AJAX地址變化狀態(tài)。這是一個(gè)可選值,可以是任何javascript類型,例如Number、String或Object。使用該保存功能的一個(gè)例子是在一個(gè)富文本編輯器中保存所有文本(比如在用戶離開當(dāng)前頁面時(shí))。當(dāng)用戶再回到這個(gè)地址時(shí),瀏覽器將會將該對象返回給歷史記錄變化監(jiān)聽器。
開發(fā)人員可以為historyData提供帶有嵌套對象和表示復(fù)雜狀態(tài)的數(shù)組的完整javascript對象;JSON (javascript Object Notation)所支持的在歷史記錄數(shù)據(jù)中都支持,包括簡單數(shù)據(jù)類型和null類型。然而,DOM對象以及可用腳本編寫的瀏覽器對象(如XMLHttpRequest)不會被保存。請注意,historyData并不隨書簽一起保存,當(dāng)瀏覽器關(guān)閉,瀏覽器緩存被清空,或者用戶清除歷史記錄的時(shí)候,它就會消失。
使用dhtmlHistory的最后一步是isFirstLoad()方法。在某些瀏覽器中,如果導(dǎo)航到一個(gè)Web頁面,再跳轉(zhuǎn)到另一個(gè)不同的頁面,然后按“后退”按鈕返回到起始的站點(diǎn),第一頁將完全重新加載,并觸發(fā)onload事件。這樣會對想要在第一次加載頁面時(shí)用某種方式對其進(jìn)行初始化(而其后則不使用這種方式重新加載該頁面)的代碼造成破壞。isFirstLoad()方法可以區(qū)分是第一次加載一個(gè)Web頁面還是用戶導(dǎo)航到保存在歷史記錄中的Web頁面時(shí)觸發(fā)的“假加載”事件。
在示例代碼中,我們只想在第一次加載頁面的時(shí)候添加歷史記錄事件;如果用戶在加載頁面后按后退按鈕返回該頁面,我們就不想重新添加任何歷史記錄事件:
window.onload = initialize;
function initialize() {
// initialize the DHTML History
// framework
dhtmlHistory.initialize();
// subscribe to DHTML history change
// events
dhtmlHistory.addListener(historyChange);
// if this is the first time we have
// loaded the page...
if (dhtmlHistory.isFirstLoad()) {
debug("Adding values to browser " "history", false);
// start adding history
dhtmlHistory.add("helloworld", "Hello World Data");
dhtmlHistory.add("foobar", 33);
dhtmlHistory.add("boobah", true);
var complexObject = new Object();
complexObject.value1 = "This is the first value";
complexObject.value2 = "This is the second data";
complexObject.value3 = new Array();
complexObject.value3[0] = "array 1";
complexObject.value3[1] = "array 2";
dhtmlHistory.add("complexObject", complexObject);
讓我們繼續(xù)使用historyStorage類。類似于dhtmlHistory,historyStorage通過一個(gè)叫historyStorage的全局對象來公開它的功能。該對象有幾個(gè)模擬散列的方法,比如put(keyName、keyValue)、get(keyName)和hasKey(keyName)。鍵名稱必須是字符串,同時(shí)鍵值可以是復(fù)雜的javascript對象甚至是XML格式的字符串。在我們的源代碼例子中,在第一次加載頁面時(shí),我們使用put()將簡單的XML放入historyStorage:
window.onload = initialize;
function initialize() {
// initialize the DHTML History
// framework
dhtmlHistory.initialize();
// subscribe to DHTML history change
// events
dhtmlHistory.addListener(historyChange);
// if this is the first time we have
// loaded the page...
if (dhtmlHistory.isFirstLoad()) {
debug("Adding values to browser " "history", false);
// start adding history
dhtmlHistory.add("helloworld", "Hello World Data");
dhtmlHistory.add("foobar", 33);
dhtmlHistory.add("boobah", true);
var complexObject = new Object();
complexObject.value1 = "This is the first value";
complexObject.value2 = "This is the second data";
complexObject.value3 = new Array();
complexObject.value3[0] = "array 1";
complexObject.value3[1] = "array 2";
dhtmlHistory.add("complexObject", complexObject);
// cache some values in the history
// storage
debug("Storing key 'fakeXML' into " "history storage", false);
var fakeXML =
'<?xml version="1.0" '
'encoding="ISO-8859-1"?>'
'<foobar>'
'<foo-entry/>'
'</foobar>';
historyStorage.put("fakeXML", fakeXML);
}
然后,如果用戶離開頁面后又通過后退按鈕返回該頁面,我們可以使用get()方法提取保存的值,或者使用hasKey()方法檢查該值是否存在。
window.onload = initialize;
function initialize() {
// initialize the DHTML History
// framework
dhtmlHistory.initialize();
// subscribe to DHTML history change
// events
dhtmlHistory.addListener(historyChange);
// if this is the first time we have
// loaded the page...
if (dhtmlHistory.isFirstLoad()) {
debug("Adding values to browser " "history", false);
// start adding history
dhtmlHistory.add("helloworld", "Hello World Data");
dhtmlHistory.add("foobar", 33);
dhtmlHistory.add("boobah", true);
var complexObject = new Object();
complexObject.value1 = "This is the first value";
complexObject.value2 = "This is the second data";
complexObject.value3 = new Array();
complexObject.value3[0] = "array 1";
complexObject.value3[1] = "array 2";
dhtmlHistory.add("complexObject", complexObject);
// cache some values in the history
// storage
debug("Storing key 'fakeXML' into " "history storage", false);
var fakeXML = '<?xml version="1.0" ' 'encoding="ISO-8859-1"?>'
'<foobar>' '<foo-entry/>' '</foobar>';
historyStorage.put("fakeXML", fakeXML);
}
// retrieve our values from the history
// storage
var savedXML = historyStorage.get("fakeXML");
savedXML = prettyPrintXml(savedXML);
var hasKey = historyStorage.hasKey("fakeXML");
var message = "historyStorage.hasKey('fakeXML')="
hasKey "<br>"
"historyStorage.get('fakeXML')=<br>"
savedXML;
debug(message, false);
}
prettyPrintXml()是一個(gè)定義在完整示例源代碼中的實(shí)用方法;此函數(shù)準(zhǔn)備在web頁面中顯示以便用于調(diào)試的簡單XML。
請注意,相關(guān)數(shù)據(jù)只在該頁面的歷史記錄中進(jìn)行持久化;如果瀏覽器被關(guān)閉,或者用戶打開一個(gè)新窗口并再次鍵入AJAX應(yīng)用程序的地址,則該歷史記錄數(shù)據(jù)對于新的Web頁面不可用。歷史記錄數(shù)據(jù)只有在用到后退或前進(jìn)按鈕時(shí)才被持久化,當(dāng)用戶關(guān)閉瀏覽器或清空緩存的時(shí)候就會消失。如果想真正長期持久化,請參閱Ajax MAssive Storage System (AMASS)。
我們的簡單示例已經(jīng)完成。
示例2:O'Reilly Mail
我們的第二個(gè)例子是一個(gè)簡單的AJAX電子郵件模擬應(yīng)用程序的示例,即O'Reilly Mail,它類似于Gmail。O'Reilly Mail描述了如何使用dhtmlHistory類來控制瀏覽器的歷史記錄,以及如何使用historyStorage對象來緩存歷史記錄數(shù)據(jù)。
O'Reilly Mail用戶界面由兩部分組成。在頁面的左邊是一個(gè)帶有不同電子郵件文件夾和選項(xiàng)的菜單,例如收件箱、草稿箱等。當(dāng)用戶選擇了一個(gè)菜單項(xiàng)(如收件箱),就用這個(gè)菜單項(xiàng)的內(nèi)容更新右邊的頁面。在一個(gè)現(xiàn)實(shí)應(yīng)用程序中,我們會遠(yuǎn)程獲取并顯示選擇的信箱內(nèi)容,不過在O'Reilly Mail中,我們只顯示已選擇的選項(xiàng)。
O'Reilly Mail使用RSH框架向?yàn)g覽器歷史記錄中添加菜單變化并更新地址欄,允許用戶利用瀏覽器的后退和前進(jìn)按鈕為應(yīng)用程序做收藏書簽和跳到上次變化的菜單。
我們添加一個(gè)特殊的菜單項(xiàng)――地址簿,以說明如何來使用historyStorage。地址簿是一個(gè)由聯(lián)系人名稱和郵件地址組成的javascript數(shù)組,在一個(gè)現(xiàn)實(shí)應(yīng)用程序中,我們會從一臺遠(yuǎn)程服務(wù)器取得這個(gè)數(shù)組。不過,在O'Reilly Mail中,我們在本地創(chuàng)建這個(gè)數(shù)組,添加幾個(gè)名稱和電子郵件地址,然后將其保存在historyStorage對象中。如果用戶離開Web頁面后又返回該頁面,那么O'Reilly Mail應(yīng)用程序?qū)⒅匦聫木彺鏅z索地址簿,而不是再次聯(lián)系遠(yuǎn)程服務(wù)器。
我們用initialize()方法保存和檢索地址簿:
/** Our function that initializes when the page
is finished loading. */
function initialize() {
// initialize the DHTML History framework
dhtmlHistory.initialize();
// add ourselves as a DHTML History listener
dhtmlHistory.addListener(handleHistoryChange);
// if we haven't retrieved the address book
// yet, grab it and then cache it into our
// history storage
if (window.addressBook == undefined) {
// Store the address book as a global
// object.
// In a real application we would remotely
// fetch this from a server in the
// background.
window.addressBook =
["Brad Neuberg 'bkn3@columbia.edu'",
"John Doe 'johndoe@example.com'",
"Deanna Neuberg 'mom@mom.com'"];
// cache the address book so it exists
// even if the user leaves the page and
// then returns with the back button
historyStorage.put("addressBook", addressBook);
}
else {
// fetch the cached address book from
// the history storage
window.addressBook = historyStorage.get("addressBook");
}
處理歷史記錄變化的代碼也很簡單。在下面的源代碼中,無論用戶按后退還是前進(jìn)按鈕,都將調(diào)用handleHistoryChange。使用O'Reilly Mail定義的displayLocation實(shí)用方法,我們可得到newLocation并使用它將我們的用戶界面更新到正確的狀態(tài)。
/** Handles history change events. */
function handleHistoryChange(newLocation,
historyData) {
// if there is no location then display
// the default, which is the inbox
if (newLocation == "") {
newLocation = "section:inbox";
}
// extract the section to display from
// the location change; newLocation will
// begin with the word "section:"
newLocation = newLocation.replace(/section/:/, "");
// update the browser to respond to this
// DHTML history change
displayLocation(newLocation, historyData);
}
/** Displays the given location in the
right-hand side content area. */
function displayLocation(newLocation,sectionData) {
// get the menu element that was selected
var selectedElement = document.getElementById(newLocation);
// clear out the old selected menu item
var menu = document.getElementById("menu");
for (var i = 0; i < menu.childNodes.length; i ) {
var currentElement = menu.childNodes[i];
// see if this is a DOM Element node
if (currentElement.nodeType == 1) {
// clear any class name
currentElement.className = "";
}
}
// cause the new selected menu item to
// appear differently in the UI
selectedElement.className = "selected";
// display the new section in the right-hand
// side of the screen; determine what
// our sectionData is
// display the address book differently by
// using our local address data we cached
// earlier
if (newLocation == "addressbook") {
// format and display the address book
sectionData = "<p>Your addressbook:</p>";
sectionData = "<ul>";
// fetch the address book from the cache
// if we don't have it yet
if (window.addressBook == undefined) {
window.addressBook = historyStorage.get("addressBook");
}
// format the address book for display
for (var i = 0; i < window.addressBook.length; i ) {
sectionData = "<li>"
window.addressBook[i]
"</li>";
}
sectionData = "</ul>";
}
// If there is no sectionData, then
// remotely retrieve it; in this example
// we use fake data for everything but the
// address book
if (sectionData == null) {
// in a real application we would remotely
// fetch this section's content
sectionData = "<p>This is section: "
selectedElement.innerHTML "</p>";
}
// update the content's title and main text
var contentTitle = document.getElementById("content-title");
var contentValue = document.getElementById("content-value");
contentTitle.innerHTML = selectedElement.innerHTML;
contentValue.innerHTML = sectionData;
}
結(jié)束語
現(xiàn)在我們已經(jīng)了解了如何使用RSH API來使AJAX應(yīng)用程序支持書簽以及后退和前進(jìn)按鈕,并提供了示例代碼,您可參考該示例來創(chuàng)建自己的應(yīng)用程序。希望您能利用書簽和歷史記錄的支持來增強(qiáng)AJAX應(yīng)用程序。
新聞熱點(diǎn)
疑難解答
圖片精選