search
HomeWeb Front-endJS TutorialpushState, replaceState, onpopstate realize forward and backward refresh of Ajax page

This article mainly introduces pushState, replaceState, and onpopstate to realize the forward and backward refresh of Ajax pages. It is very good and has certain reference value. Friends who need it can refer to it.

Using Ajax can Obtaining data asynchronously can render the page more efficiently.

But there are also some problems:

Refresh the page, the page will become the initial state

Browse The forward and backward functions of the browser are invalid

It is not friendly to search engine crawlers

1.

In the past, the hash anchor point of the browser was used to solve the problem

Different hashes mark different parts of the page, which can correct the problem of incorrect page refresh data

Then monitor the change of hash anchor point through the onhashchange event, and manually perform forward and backward operations, browser support

2,

Then a hashbang technology appeared, that is, adding the tag #!/myPath after the url to solve the above problem

Define a page part through a path, which is commonly seen in single-page applications (already encapsulated in Angular). But it seems that only Google really supports crawling this path

3,

The new features of HTML5 have helped, through the two new history methods of pushState and replaceState and the onpopstate window event, solving the above three problems

Of course, because it is a new feature of HTML5, it is not well supported by older browsers. It is recommended to use the hashbang method for compatibility

This article mainly talks about these new things like pushState

The text is too boring, let’s take a look at the diagram and click directly to feel

The purpose of this chestnut is: The initial value is 0. It increments through asynchronous requests. You can go forward or backward and refresh. You can also get the corresponding data after opening a new url.

history.pushState(state, title, url)
history.replaceState(state, title, url)

Among them, state is a json object that can be customized to store some data. Title That is, the tag title corresponding to this url (but it seems that browsers ignore this parameter)

url is the tag url of a certain page (the operation will only change the url in the address bar, and will not load the url immediately. , you can simply mark ?w=a, ajaxPage.html/w=a, &w=a, it is just a mark, just compare it when taking the value)

The difference between replaceState and pushState is: the former directly Replace the current value, which is to push a value into the stack

After the window.onpopstate event is triggered, the first json object of the above method can be obtained through history.state

Implementation part

HTML

<p class="push-state-test">
<input type="button" id="ajax-test-btn" value="Ajax获取">
<p>value: <span id="ajax-test-val">0</span></p>
</p>

JS

var $val = $(&#39;#ajax-test-val&#39;),
// 获取当前页面的标记
m = window.location.search.match(/\?val=(\d+)/);
// 新进入页面,通过url中的标记初始化数据
if (m) {
increaseVal(m[1] - 1);
}
// 请求
function increaseVal(val) {
$.post(&#39;ajax-test.php&#39;, {
val: val
}, function(newVal) {
$val.text(newVal);
// 存储相关值至对象中
var state = {
val: newVal,
title: &#39;title-&#39; + newVal,
url: &#39;?val=&#39; + newVal
}
// 将相关值压入history栈中
window.history.pushState && window.history.pushState(state, state.title, state.url);
});
}
$(&#39;#ajax-test-btn&#39;).click(function() {
increaseVal(parseInt($val.text(), 10));
});
// 浏览器的前进后退,触发popstate事件
window.onpopstate = function() {
var state = window.history.state;
console.log(state)
// 直接将值取出,或再次发个ajax请求
$val.text(state.val);
window.history.replaceState && window.history.replaceState(state, state.title, state.url);
};

PHP

<?php
$val = $_REQUEST[&#39;val&#39;];
echo $val + 1;
?>

Here, different ajax result pages are marked by ?val=num

Tips:

After using pushState, the current forward and backward triggers the popstate event, and the corresponding json object is obtained.

The data of the json object can be customized

It can be simply Store the relevant tag and send a request, or directly save the result corresponding to the tag page

With the back operation, the address bar URL is updated, and the asynchronous data is also updated

Refresh the page or open a new page, you must request data according to the tag in the url

It should be remembered that the browser will not automatically load the asynchronous content page corresponding to the tag in this part of the url. Let's get

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

AJAX request queue implementation

##Summary of several methods of using ajax to submit forms asynchronously

How to solve the problem of arrays in AJAX requests

The above is the detailed content of pushState, replaceState, onpopstate realize forward and backward refresh of Ajax page. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function