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 <script>document.write(new The Date());</script> 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The steps to register an Ouyi account are as follows: 1. Prepare a valid email or mobile phone number and stabilize the network. 2. Visit Ouyi’s official website. 3. Enter the registration page. 4. Select email or mobile phone number to register and fill in the information. 5. Obtain and fill in the verification code. 6. Agree to the user agreement. 7. Complete registration and log in, carry out KYC and set up security measures.

The browser's unresponsive method after the WebSocket server returns 401. When using Netty to develop a WebSocket server, you often encounter the need to verify the token. �...

To safely download the Binance APP, you need to go through the official channels: 1. Visit the Binance official website, 2. Find and click the APP download portal, 3. Choose to scan the QR code, app store, or directly download the APK file to download to ensure that the link and developer information are authentic, and enable two-factor verification to protect the security of the account.

Generating a WeChat applet QR code with parameters in Java and displaying it on an HTML page is a common requirement. This article will discuss in detail how to use J...

Confusion and answers about JWT and Session Many beginners are often confused about their nature and applicable scenarios when learning JWT and Session. This article will revolve around J...

Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...

After the USDT transfer address is incorrect, first confirm that the transfer has occurred, and then take measures according to the error type. 1. Confirm the transfer: view the transaction history, obtain and query the transaction hash value on the blockchain browser. 2. Take measures: If the address does not exist, wait for the funds to be returned or contact customer service; if it is an invalid address, contact customer service and seek professional help; if it is transferred to someone else, try to contact the payee or seek legal help.

EU MiCA compliance certification, covering 50 fiat currency channels, cold storage ratio 95%, and zero security incident records. The US SEC licensed platform has convenient direct purchase of fiat currency, a ratio of 98% cold storage, institutional-level liquidity, supports large-scale OTC and custom orders, and multi-level clearing protection.
