Use AJAX to control bookmarks and fallback buttons

Source: Internet
Author: User
Tags format array hash html form include new set version javascript array
ajax| Button | control | Bookmark This article describes an open source JavaScript library that supports AJAX application bookmarks and fallback buttons. At the end of this guide, developers will come up with an AJAX solution that isn't even Google Maps or Gmail: Robust, usable bookmarks and forward-backwards actions work as correctly as other Web pages.
  
Ajax: How to control bookmarks and rollback buttons This article illustrates an important achievement, with AJAX applications currently facing the application of bookmarks and fallback buttons, describing a very simple historical library (really simplicity History), an open source solution to this type of problem, and provides some examples that can be run.
  
The main problem described in this article is twofold, one is a hidden HTML form used as a session cache of client information for a large and short lifecycle, and this cache is strong for forward fallback on this page. The second is an anchor connection and a hidden iframes combination used to intercept and record the browser's historical events to implement the Forward and rewind buttons. Both of these technologies are encapsulated in a simple JavaScript library for the benefit of developers.
  
   the problems that exist
  
Bookmarks and fallback buttons run smoothly on traditional, multiple-page Web applications. When users surf the web, their browser address bar updates the URL, which can be pasted into the email or added to the bookmark for later use. The fallback and forward buttons can also work correctly, allowing users to move between the pages they visit.
  
Ajax apps are different, but he's also a mature program on a single Web page. The browser is not made for Ajax-ajax he captures past events when web Apps refresh the page with each mouse click.
  
In Ajax-like Gmail software, the browser's address bar stays in the right position as the user chooses and changes the state of the application, making it impossible to bookmark a particular application view. In addition, if the user presses their fallback button to return to the previous operation, they will be amazed to find that the browser will completely leave the Web page of his application.
  
   Solution
  
The open source really Simply History (RSH) framework addresses these issues, and he brings with it the ability to bookmark and control the forward back button for AJAX applications. RSH is currently a beta version, on Firefox1.0, Netscape7 and above, and IE6 and above run. Safari is not yet supported (for a more detailed description, see the article in my weblog coding in Paradise:Safari:No DHTML History Possible).
  
There are several AJAX frameworks that can help us bookmark and publish history, but all frameworks are plagued by several important bugs because of their implementation (see Coding in Paradise:ajax History libraries for details). In addition, many of the AJAX history framework integrations are bound to larger libraries, such as Backbase and Dojo, which provide a different programming model than traditional AJAX applications, forcing developers to adopt a whole new set of ways to get the browser's history-related functionality.
  
Accordingly, RSH is a simple model that can be included in an existing AJAX system. Also, the really Simple history library uses techniques to avoid bugs that affect other historical frameworks.
  
The really simple history framework consists of 2 JavaScript class libraries, called Dhtmlhistory and Historystorage respectively.
  
The Dhtmlhistory class provides a feature that extracts history from Ajax applications. Ajax page Add () historical event to the browser, specify a new address and associated historical data. The Dhtmlhistory class uses an anchor hash table to update the browser's current URL, such as #new-location, and then associates historical data with this new URL. Ajax applications register themselves into the history listener, and then when the user navigates with the forward and rewind buttons, the history event is fired, provided to the browser's new address and calls Add () to persist the data.
  
The second class, Historystorage, allows developers to store historical data of any size. General pages, when a user navigates to a new Web site, the browser unloads and clears all application and JavaScript state information for this page. If the user returns with the fallback button, all data is lost. The Historystorage class solves this problem by having an API containing simple Hashtable methods such as put (), get (), Haskey (). These methods allow developers to store data of any size when they leave a Web page, and the data can be accessed through the Historystorage class when the user points back to the rollback button. We do this by using a hidden table fields (a hidden form field) that uses the browser to automatically save this feature of the form field value even when the user leaves the Web page.
  
Let's go to a simple example immediately.
  
   Example 1
  
First, any page that wants to use the really simple history framework must include (include) Dhtmlhistory.js scripts.
  
<!--Load The really simple History framework--><script type= "Text/javascript" src= ". /.. /framework/dhtmlhistory.js "></script>
  
The DHTML History application must also contain a specified file called blank.html in the same directory as the AJAX Web page, which is bound by the really simple History framework and is required for IE. On the other hand, Rsh uses a hidden iframe to track and join the change of IE history, in order to perform the function correctly, this IFRAME needs to point to a real address and does not need blank.html.
  
The RSH framework creates a global object called Dhtmlhistory, which serves as an entry point for manipulating browser history. The first step in using Dhtmlhistory is to initialize the object after the page has been loaded.
  
Window.onload = Initialize; function Initialize () {//Initialize the DHTML History//Framework dhtmlhistory.initialize ();
  
The developer then uses the Dhtmlhistory.addlistener () method to subscribe to historical change events. This method obtains a JavaScript callback method, and when a DHTML history Change event occurs, he receives 2 arguments, a new page address, and any optional historical data that can be associated with this event.
  
Indow.onload = Initialize;  function Initialize () {//Initialize the DHTML History//Framework dhtmlhistory.initialize (); Subscribe to DHTML History Change//Events Dhtmlhistory.addlistener (Historychange);
  
The Historychange () method is simple and easy to understand, consisting of a new address (newlocation) that is received after a user navigates to a new address, and an optional historical data Historydata associated with the event.
  
/** we callback to receive history the change events. */function Historychange (NewLocation, Historydata) {debug ("A History change has occurred:" + "newlocation= "+newlocation +", Historydata= "+historydata, true";}
  
The debug () method used above is a tool function defined in the example code, in the complete download example. The debug () method simply beats a message on a Web page, the 2nd Boolean variable, which is true in the code, and whether to purge all previously existing messages before printing a new debug message.
  
A developer uses the Add () method to add a history event. Adding a historical event involves specifying a new address based on historical changes, like "edit:somepage" tags, and also provides an option to be stored to historical data Historydata values when an event occurs.
  
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 the have//loaded the page ... if (Dhtmlhistory.isfirstload ()) {debug (Adding values to brow  Ser "+" 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";  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);
  
After the Add () method is invoked, the new address is immediately displayed as an anchor value in the user's browser's URL bar. For example, an AJAX Web page stays in Http://codinginparadise.org/my_ajax_app, calls Dhtmlhistory.add ("HelloWorld", "Hello World Data", The user will see the following address in the browser's URL bar
Http://codinginparadise.org/my_ajax_app#helloworld
  
Then they can bookmark this page, and if they use this bookmark, your AJAX application can read the #helloworld value and use her to initialize the Web page. The address value in the hash is explicitly encoded and decoded by the really simple History framework (URL encoded and decoded) (this is to resolve the character encoding problem)
  
Historydata is more useful than an easier way to match a URL when the Ajax address changes to save more complex states. He is an optional value that can be any type of JavaScript, such as number, String, or Object type. There is an example of using this in a multiple text editor (Rich text editor) to save all the text, for example, if the user drifts from this page (or from the page to another page, away from the page). When a user returns to this address, the browser will return the object to the historical change listener (history changes listener).
  
Developers can provide a fully historydata JavaScript object, depicting complex states with nested objects objects and arranging arrays. As long as the JSON (JavaScript Object notation) allows it, it is allowed in historical data, including simple data types and null type. DOM objects and programmable browser objects such as XMLHttpRequest are not saved. Note that Historydata will not be persisted by bookmarks, if the browser is turned off, or if the browser's cache is emptied, or when the user clears history, it disappears.
  
The last step in using Dhtmlhistory is the Isfirstload () method. If you navigate to a Web page, jump to a different page, and then press the rewind button to return to the starting web, the first page will be completely reloaded and the OnLoad event is fired. This can be disruptive and will not refresh the page when the code wants to initialize the page in some way at the first load. The Isfirstload () method makes it possible for the difference to be the first time the page is loaded, or relative, to trigger the Load event when the user navigates back to the page recorded in his own browser history.
  
In the example code, we just want to join the history event on the first page load, and if the user returns to the page by pressing the rollback button after the first load, we don't want to rejoin any historical events.
  
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 the have//loaded the page ... if (Dhtmlhistory.isfirstload ()) {debug (Adding values to brow  Ser "+" 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";  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);
  
Let's continue using the Historystorage class. Like Dhtmlhistory, Historystorage shows his function through a single global object called Historystorage, which has several methods to disguise as a hash table, like put (KeyName, keyvalue) , get (KeyName), and Haskey (KeyName). The key name must be a character, and the key value can be a complex JavaScript object or even an XML-formatted character. In our example of source code, we put () simple XML to historystorage the first time the page is loaded.
  
  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 the have//loaded the page ... if (Dhtmlhistory.isfirstload ()) {debug (Adding values to brow  Ser "+" 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";  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/&gt   ;'  + ' </foobar> '; Historystorage.put ("Fakexml", fakexml); }
  
Then, if the user drifts away from this page (navigating away) and returns via the return button, we can use get () to present our stored values or Haskey () to check if he exists.
  
  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 the have//loaded the page ... if (Dhtmlhistory.isfirstload ()) {debug (Adding values to brow  Ser "+" 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";  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/&gt   ;'  + ' </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 () is a first in the example source code full example source code in the tool method. This method prepares a simple XML display on the Web page for easy debugging.
  
Note that the data is persisted only when using the history of the page, if the browser is closed, or if the user opens a new window and then retype the AJAX application's address, historical data is not available for these new Web pages. Historical data is persisted only when the forward or rollback button is used, and disappears when the user closes the browser or empties the cache. For real long persistence, see Ajax massive Storage System (AMASS).
  
Our simple example has been completed. Demo He (demo it) or download all the source code (download the full source code.)
  
   Example 2
  

Our 2nd example is an example of a simple analog Ajax email application called o ' Reilly Mail, similar to Gmail. O ' Reilly Mail describes how to use the Dhtmlhistory class to control the history of the browser and how to use the Historystorage object to cache historical data.
  
The O ' Reilly Mail user Interface (interface) has two parts. On the left side of the page is a menu with different email folders and options, such as Inbox, Drafts, and so on. When a user selects a menu item, such as an inbox, we update the page on the right with the contents of the item. In a practical application, we will remotely obtain and display the choice of the mailbox content, but in O ' Reilly mail, we simply display the selected option.
  
O ' Reilly Mail uses the really simple History framework to add menu changes and update address bars to browser history, allowing users to bookmark and jump to the previous change menu using the browser's fallback and forward buttons.
  
We add a special menu item, Address Book, to describe how historystorage can be used. The Address Book is a JavaScript array of contact name emails and addresses, and in a real application we will get him from a remote server. However, in O ' Reilly mail, we create this array locally, add several name emails and addresses, and then store them in the Historystorage object. If the user leaves the Web page and returns, the O ' Reilly mail application gets the address book from the cache again, rather than (having to) access the remote server again.
  
The address book is stored and initialize in our initialization () method.
  
  /** our function This 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 to our//history storage if (Window.ad   Dressbook = = 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 ' m        Om@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"); }
  
The code to handle historical changes is simple. In the following code, the Handlehistorychange is invoked when the user returns the Forward button regardless of the next refund. We get a new address (newlocation) using his update our user interface to change the state by using a tool called Displaylocation o ' Reilly mail.
  
  /** 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'll//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 content area. */function displaylocation (NewLocation, Sectiondata) {//get "the menu element that is selected Var selecte        Delement = document.getElementById (newlocation);  Clear out of 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.clas   sname = ""; }//Cause the new selected menu item to//appear differently the UI SELECTEDELEMENT.CLASSN   Ame = "selected"; Display the new section on the right-hand//side of the screen; Determine what//our sectiondata are//display the address book differently by//using our local address data we CAC Hed//earlier if (NewLocation = "AddressBook") {//format and display the Address Book Sectiondata = "<p>yo   ur 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 here example//We use fake data for everything but the//address Book if (Sectiondata = null) {//in a real AP Plication we would remotely//Fetch this section ' s content sectiondata = "<p>this are:" + Selectede   lement.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;}
  
Demo (Demo) O ' Reilly mail or download (download) O ' Reilly Mail source code.
  
   Concluding remarks
  
You've now learned to use the really simple History API to get your Ajax apps to respond to bookmarks and forward rewind buttons, and there's code that can be used as a source for creating your own applications. I eagerly look forward to your use of bookmarks and historical support to complete your AJAX creations.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.