Home > Article > Web Front-end > Two Ajax solutions to retain browser history
I always download something from github. The entire interface of github is well made and the experience is very good. I like the special effect of the source code sliding the most. At first I thought this was just an ordinary ajax request effect, but I found that this special effect can lead to browsing. The address bar of the server will follow the changes, and you can slide the code back and out after clicking the forward and back buttons~~ So let’s study it~
1. Implementation through anchor point Hash:
In fact, this aspect has been done in China for a long time, such as Taobao Illustrated, which is achieved by adding # anchor point after the address bar. The browser can identify the historical records in units of anchor points. But it does not mean that the page itself has this anchor point. The Hash of the anchor point only serves to guide the browser to push this record to the top of the history stack.
Let’s make a small demo:
<style type="text/css"> #tab1_header,#tab2_header{ cursor:pointer; border:1px solid; width:50px; } #tab1,#tab2{ width:90%; height:200px; border:1px solid; } </style> <p id="tab_header"> <span id="tab1_header">Tab1</span> <span id="tab2_header">Tab2</span> </p> <p id="tab1">1</p> <p id="tab2">2</p>
A very simple Tab switch, if it is direct under normal circumstances:
$("#tab1_header").click(function() { $("#tab2").hide(); $("#tab1").show(); }); $("#tab2_header").click(function() { $("#tab1").hide(); $("#tab2").show(); });
But if you want to use the back button to return to tab1 when you click tab2, it will not work. If you refresh, the behavior of the browser is not at all based on the user's ideas. In this case, we can add # anchor to simulate a new page. Why do we say For simulation, if you change window.location directly through js, the browser will reload the page, but adding # will not reload it and can be saved in the history. JS uses window.location.hash to control the anchor point # behind the URL.
We change the code to this:
$(function(){ showTab(); $(window).bind('hashchange', function(e){ showTab(); }); $("#tab1_header").click(showTab1); $("#tab2_header").click(showTab2); }); function showTab() { if (window.location.hash == "#tab2"){ showTab2(); } else { showTab1(); } } function showTab1() { $("#tab2").hide(); $("#tab1").show(); window.location.hash = "#tab1"; }; function showTab2() { $("#tab1").hide(); $("#tab2").show(); window.location.hash = "#tab2"; };
Just add window.location.hash = "#tab1". After clicking tab, #tab1 will be added after the address bar. After clicking tab2, it will be changed to #tab2. When the browser detects the url change When the hashchange event is triggered, the event that the user can get when clicking back can be judged through window.location.hash and perform ajax operations. However, the haschange event is not available in every browser. Only modern advanced browsers have it, so polling is needed in low-level browsers to detect whether the URL is changing. This will not be discussed in detail here.
2. Implementation through HTML5 enhanced History object (like Pjax)
You can update the browser address bar without refreshing through the window.history.pushState method. This method pushes the address into the history stack while updating the address bar. To remove the top page of the stack, you can use the popstate event to capture it. ~
Let’s simulate the github environment. Each url in github corresponds to a complete actual page, so when requesting the page with ajax, you need to asynchronously obtain the content in the specified id container in the target page:
For example, there are two pages like this:
index.html
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gbk"> <title>index</title> </head> <body> <script>document.write(new Date());</script> <p id="cn"> <a href="second.html">加载前</a> </p> </body> </html>
second.html
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gbk"> <title>second</title> </head> <body> <script>document.write(new Date());</script> <p id="cn"> <a href="index.html">加载后</a> </p> </body> </html>
If it is opened with a synchronous http request, it will be two pages. If the two pages have many similarities, we can use this method to implement the ajax request to change the DOM. I added 3f1c4e4b6b16bbbd69b2ee476dc4f83adocument.write(new The Date());2cacc6d41bbb37262a98f745aa00fbf0 statement can be used to know whether it is taken from two http requests through its changes. Bureau
The external ajax request will not change the time display.
$(function() { var state = { title: "index", url: "index.html" }; $("#cn").click(function() { window.history.pushState(state, "index", "second.html"); var $self = $(this); $.ajax({ url: "second.html", dataType: "html", complete: function(jqXHR, status, responseText) { responseText = jqXHR.responseText; if (jqXHR.isResolved()) { jqXHR.done(function(r) { responseText = r; }); $self.html($("<p>").append(responseText.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")).find("#cn")); } } }); document.title = "second"; return false; }); $(window).bind('popstate', function(e) { var st = e.state; //$("#cn").load(st.url + " #cn"); $.ajax({ url: "index.html", dataType: "html", complete: function(jqXHR, status, responseText) { responseText = jqXHR.responseText; if (jqXHR.isResolved()) { jqXHR.done(function(r) { responseText = r; }); $("#cn").html($("<p>").append(responseText.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")).find("#cn")); } } }); document.title = e.state.title; }); });
In the above statement, when the #cn element is clicked, the state is pushed into the history stack through the pushState method, and in the third parameter, the browser URL box points to the second page, and the second page is loaded asynchronously through ajax, and the corresponding part is added to the container, thus realizing asynchronous loading and changing the address bar URL. Similarly, when the user clicks back, popstate is triggered. The first parameter state in the pushState method just now is the state in the formal parameter e passed in here. Attributes are taken out through var st = e.state for development use. At the same time, the corresponding content in the index page is loaded. Due to limited time, this js has not been reconstructed, so I wrote $.ajax directly. In fact, if you do not need any special effects and simply load asynchronously in jQ, you can directly use $("#cn").load(st.url + " #cn ");Put the #cn corresponding to the requested HTML into the #cn container of this page. However, if you want to add more dazzling special effects, you must directly operate the data returned by ajax.
$("#cn").html($("<p>").append(responseText.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")).find("#cn"));
First create a p container, then load the script-filtered code into this container. Use the find method to find the corresponding selector container and insert it into your own page. You don’t need to fill it with html here. You can use slideUp according to your own project needs. Show what special effects to display the content~~
In addition, I would like to recommend a jQuery component called pjax (https://github.com/defunkt/jquery-pjax). It is a relatively cool component. The asynchronous part loads into another page corresponding to the content in the container. The implementation mechanism and Same as my second option above. pushState + ajax = pjax I feel like this application will become popular.
To sum up, the two solutions are actually not very good at supporting lower-level browsers such as IE6 or FF3.6. The former needs to use polling to monitor the browser address bar behavior if it is to be compatible with low-end browsers, while the latter is A complete HTML5 application can only make judgment jumps for non-HTML5 browsers.
如pjax最后的一段无奈的兼容处理:
$.support.pjax = window.history && window.history.pushState // Fall back to normalcy for older browsers. if ( !$.support.pjax ) { $.pjax = function( options ) { window.location = $.isFunction(options.url) ? options.url() : options.url } $.fn.pjax = function() { return this } }
The above is the detailed content of Two Ajax solutions to retain browser history. For more information, please follow other related articles on the PHP Chinese website!