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 solutions for Ajax to retain browser history. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software