服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > 专题栏目 > WEB2.0新技术 > 查看文档

ajax:如何处理书签和后退按钮

  本文将展示一个开源javascript库,该脚本库给ajax应用程序带来了书签和后退按钮支持。在学习完这个教程后,开发人员将能够获得对一个ajax问题的解决方案(甚至连google maps和gmail现在都不提供该解决方案):一个强大的、可用的书签和后退前进功能,其操作行为如同其他的web应用程序一样。

      本文将展示一个开源javascript库,该脚本库给ajax应用程序带来了书签和后退按钮支持。在学习完这个教程后,开发人员将能够获得对一个ajax问题的解决方案(甚至连google maps和gmail现在都不提供该解决方案):一个强大的、可用的书签和后退前进功能,其操作行为如同其他的web应用程序一样。

  本文将阐述目前ajax应用程序在使用书签和后退按钮方面所面临的严重问题;展示really simple history(rsh)库――一个可以解决以上问题的开源框架,并提供几个运行中的例子。

  本文所展示的这个框架的主要发明分为两部分。首先是一个隐藏的html表单,用于缓存大量短期会话的客户端信息;这种缓存功能为页面导航提供了强大的支持。其次是超链接锚点和隐藏iframe的组合,它们被嵌入后退和前进按钮,用来截获和记录浏览器的历史记录事件。以上两种技术都被包装在一个简单的javascript库中来简化开发。

问题

  书签和后退按钮在传统的多页面web应用程序中运行得非常好。当用户浏览web站点的时候,其浏览器的地址栏记录随新的url而更新,这些记录可以被粘贴到电子邮件或者书签中供以后使用。后退和前进按钮也可以正常操作,使用户可以在访问过的页面中向前或向后翻动。

  但是ajax应用程序却不一样,它们是运行在单个web页面中的复杂程序。浏览器并不是为这类程序而构建的――这类web应用程序已经过时,它们在每次鼠标点击的时候都需要重新刷新整个页面。

  在这种类似于gmail的ajax软件中,浏览器的地址栏在用户选择功能和改变程序状态的时候保持不变,这使得无法在特定的应用程序视图中使用书签。此外,如果用户按下“后退”按钮来“撤销”上次的操作,他们会惊奇地发现,浏览器会完全离开该应用程序的web页面。

解决方案

  开源rsh框架可以解决这些问题,它为ajax应用程序提供了书签和控制后退、前进按钮的功能。rsh目前还处于beta阶段,可以在firefox 1.0、netscape 7+、internet explorer 6+等浏览器上运行;目前还不支持safari(有关说明,请参见我的文章“coding in paradise: safari: no dhtml history possible”)。

  目前有几个ajax框架对书签和历史记录问题有所帮助;但这些框架目前都有几个由于实现而造成的重大bug(有关详细信息,请参见“coding in paradise: ajax history libraries”)。此外,很多ajax历史记录框架被绑定到较大的库上,例如backbase和dojo;这些框架为ajax应用程序引入了完全不同的编程模型,迫使开发人员使用全新的方式来获得历史记录功能。

  相较之下,rsh是一个可以包含在现有ajax系统中的简单模块。此外,rsh库采用了一些技术以避免产生影响其他历史记录框架的bug。

  rsh框架由两个javascript类组成:dhtmlhistory和historystorage。

  dhtmlhistory类为ajax应用程序提供历史记录抽象。ajax页面使用add()方法添加历史记录事件到浏览器,指定新的地址和相关的历史记录数据。dhtmlhistory类使用一个锚散列(如#new-location)更新浏览器当前的url,同时把历史记录数据和该新url关联。ajax应用程序将自己注册为历史记录的监听器,当用户使用后退和前进按钮进行浏览时,历史记录事件被触发,为浏览器提供新的位置以及与add()调用一起保存的任何历史记录数据。

  第二个类:historystorage,允许开发人员保存任意数量的已存历史记录数据。在普通web页面中,当用户导航到一个新的web站点时,浏览器卸载并清除web页面上的所有应用程序和javascript状态;如果用户用后退按钮返回,所有的数据都丢失了。historystorage类通过一个包含简单散列表方法(例如put()、get()、haskey())的api来解决这类问题。上面的方法允许开发人员在用户离开web页面之后保存任意数量的数据;当用户按后退按钮重新返回时,历史记录数据可以通过historystorage类来访问。在内部,我们通过使用隐藏的表单字段来实现此功能,这是因为浏览器会自动保存表单字段中的值,甚至在用户离开web页面的时候也如此。

例子

  让我们先从一个简单的例子开始。

  首先,任何需要使用rsh框架的页面都必须包含dhtmlhistory.js脚本:

<!-- load the really simple 
     history framework -->
<script type="text/javascript"
        src="../../framework/dhtmlhistory.js">
</script>

  dhtml历史记录应用程序也必须在与ajax web页面相同的目录下包含blank.html文件;这个文件与rsh框架打包在一起,且对于internet explorer来说是必需的。顺便提一下,rsh使用一个隐藏iframe来跟踪和添加internet explorer的历史记录变化;这个iframe需要我们指定一个实际的文件位置才能正常工作,这就是blank.html。

  rsh框架创建了一个叫做dhtmlhistory的全局对象,这是操纵浏览器历史记录的入口点。使用dhtmlhistory的第一步是在web页面加载完成后初始化dhtmlhistory对象:

window.onload = initialize;
    
function initialize() {
  // initialize the dhtml history
  // framework
  dhtmlhistory.initialize();

  然后,开发人员使用dhtmlhistory.addlistener()方法订阅历史记录变化事件。这个方法带有一个javascript回调函数,当dhtml历史记录变化事件发生时,该函数接收两个参数:新的页面位置以及任何可与该事件关联的可选历史记录数据:

window.onload = initialize;
    
function initialize() {
  // initialize the dhtml history
  // framework
  dhtmlhistory.initialize();
  
  // subscribe to dhtml history change
  // events
  dhtmlhistory.addlistener(historychange);

  historychange()方法很简单,该函数在用户导航到一个新位置后接收newlocation以及任何与该事件关联的可选historydata。

/** our callback to receive history change
     events. */
function historychange(newlocation, 
                       historydata) {
  debug("a history change has occurred: "
        + "newlocation="+newlocation
        + ", historydata="+historydata, 
        true);
}

  上面用到的debug()方法是定义在示例源文件中的一个实用函数,它与完整示例打包在一起供下载。debug()只是用来将消息打印到web页面上;第二个布尔型参数(在上述代码中值为true)控制是否在打印新的调试消息之前清除原有的全部消息。

  开发人员使用add()方法添加历史记录事件。添加历史记录事件涉及为历史记录变化指定一个新地址,例如edit:somepage,以及提供一个和该事件一起保存的可选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()被调用之后,新的地址将立即作为一个锚值(链接地址)显示在浏览器的url地址栏中。例如,对地址为http://codinginparadise.org/my_ajax_app的ajax web页面调用dhtmlhistory.add("helloworld", "hello world data")之后,用户将会在其浏览器url地址栏中看到如下的地址:

http://codinginparadise.org/my_ajax_app#helloworld   然后用户可以将这个页面做成书签,如果以后用到这个书签,ajax应用程序可以读取#helloworld值,并用它来初始化web页面。散列后面的地址值是rsh框架可以透明编码和解码的url地址。

  historydata非常有用,它保存比简单的url更为复杂的ajax地址变化状态。这是一个可选值,可以是任何javascript类型,例如number、string或object。使用该保存功能的一个例子是在一个富文本编辑器中保存所有文本(比如在用户离开当前页面时)。当用户再回到这个地址时,浏览器将会将该对象返回给历史记录变化监听器。

  开发人员可以为historydata提供带有嵌套对象和表示复杂状态的数组的完整javascript对象;json (javascript object notation)所支持的在历史记录数据中都支持,包括简单数据类型和null类型。然而,dom对象以及可用脚本编写的浏览器对象(如xmlhttprequest)不会被保存。请注意,historydata并不随书签一起保存,当浏览器关闭,浏览器缓存被清空,或者用户清除历史记录的时候,它就会消失。

  使用dhtmlhistory的最后一步是isfirstload()方法。在某些浏览器中,如果导航到一个web页面,再跳转到另一个不同的页面,然后按“后退”按钮返回到起始的站点,第一页将完全重新加载,并触发onload事件。这样会对想要在第一次加载页面时用某种方式对其进行初始化(而其后则不使用这种方式重新加载该页面)的代码造成破坏。isfirstload()方法可以区分是第一次加载一个web页面还是用户导航到保存在历史记录中的web页面时触发的“假加载”事件。

  在示例代码中,我们只想在第一次加载页面的时候添加历史记录事件;如果用户在加载页面后按后退按钮返回该页面,我们就不想重新添加任何历史记录事件:

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);

  让我们继续使用historystorage类。类似于dhtmlhistory,historystorage通过一个叫historystorage的全局对象来公开它的功能。该对象有几个模拟散列的方法,比如put(keyname、keyvalue)、get(keyname)和haskey(keyname)。键名称必须是字符串,同时键值可以是复杂的javascript对象甚至是xml格式的字符串。在我们的源代码例子中,在第一次加载页面时,我们使用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()是一个定义在完整示例源代码中的实用方法;此函数准备在web页面中显示以便用于调试的简单xml。

  请注意,相关数据只在该页面的历史记录中进行持久化;如果浏览器被关闭,或者用户打开一个新窗口并再次键入ajax应用程序的地址,则该历史记录数据对于新的web页面不可用。历史记录数据只有在用到后退或前进按钮时才被持久化,当用户关闭浏览器或清空缓存的时候就会消失。如果想真正长期持久化,请参阅ajax massive storage system (amass)。

示例2:o'reilly mail

  我们的第二个例子是一个简单的ajax电子邮件模拟应用程序的示例,即o'reilly mail,它类似于gmail。o'reilly mail描述了如何使用dhtmlhistory类来控制浏览器的历史记录,以及如何使用historystorage对象来缓存历史记录数据。

  o'reilly mail用户界面由两部分组成。在页面的左边是一个带有不同电子邮件文件夹和选项的菜单,例如收件箱、草稿箱等。当用户选择了一个菜单项(如收件箱),就用这个菜单项的内容更新右边的页面。在一个现实应用程序中,我们会远程获取并显示选择的信箱内容,不过在o'reilly mail中,我们只显示已选择的选项。

  o'reilly mail使用rsh框架向浏览器历史记录中添加菜单变化并更新地址栏,允许用户利用浏览器的后退和前进按钮为应用程序做收藏书签和跳到上次变化的菜单。

  我们添加一个特殊的菜单项――地址簿,以说明如何来使用historystorage。地址簿是一个由联系人名称和邮件地址组成的javascript数组,在一个现实应用程序中,我们会从一台远程服务器取得这个数组。不过,在o'reilly mail中,我们在本地创建这个数组,添加几个名称和电子邮件地址,然后将其保存在historystorage对象中。如果用户离开web页面后又返回该页面,那么o'reilly mail应用程序将重新从缓存检索地址簿,而不是再次联系远程服务器。

  我们用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");
   }

  处理历史记录变化的代码也很简单。在下面的源代码中,无论用户按后退还是前进按钮,都将调用handlehistorychange。使用o'reilly mail定义的displaylocation实用方法,我们可得到newlocation并使用它将我们的用户界面更新到正确的状态。

/** 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;
}
  

结束语

  现在我们已经了解了如何使用rsh api来使ajax应用程序支持书签以及后退和前进按钮,并提供了示例代码,您可参考该示例来创建自己的应用程序。希望您能利用书签和历史记录的支持来增强ajax应用程序。

查看原文      下载本文示例源码

扫描关注微信公众号