Home Web Front-end JS Tutorial Example of using ajax and history.pushState to change the page URL without refreshing_AJAX related

Example of using ajax and history.pushState to change the page URL without refreshing_AJAX related

May 25, 2018 pm 03:21 PM
ajax Change

This article mainly introduces the example of using ajax and history.pushState to change the page URL without refreshing. Friends in need can refer to the following

Performance

If you use When you visit this blog, github.com, plus.google.com and other websites with browsers such as chrome or firefox, if you are careful, you will find that clicks between pages are requested asynchronously through ajax, and the URL of the page changes at the same time. And it can support browser forward and backward very well.

What is it that has such a powerful function?

HTML5 references new APIs, history.pushState and history.replaceState, which are used to change the page URL without refreshing.
Differences from traditional AJAX

Traditional ajax has the following problems:

1. You can change the page content without refreshing, but you cannot change the page URL

2. For better accessibility, after the content changes, the hash of the URL is usually changed

3. The hash method cannot handle the browser's forward and backward issues well!

4. Furthermore, the browser has introduced the onhashchange interface. Browsers that do not support it can only periodically determine whether the hash has changed.

5. However, this method is very unfriendly to search engines

6. Twitter and Google have agreed to use #!xxx (that is, the first character of hash is!), and search engines support it.

In order to solve the problems caused by traditional ajax, new APIs have been introduced in HTML5, namely: history.pushState, history.replaceState

You can operate the browser history through the pushState and replaceState interfaces, and Change the URL of the current page.

pushState is to add the specified URL to the browser history, and replaceState is to replace the current URL with the specified URL.

How to use

<strong style="border-color: initial; border-width: 0px; padding: 0px; margin: 0px;">var state = { 
title: title, 
url: options.url, 
otherkey: othervalue 
}; 
window.history.pushState(state, document.title, url);</strong>
Copy after login

In addition to the title and url, you can also add other data to the state object. For example: you also want to configure some ajax configurations for sending Save it.

replaceState and pushState are similar, so I won’t introduce them much here.
How to respond to the browser's forward and backward operations

The onpopstate event is provided on the window object. The state object passed above will become a sub-object of the event, so that the stored title and URL can be obtained.

window.addEventListener(&#39;popstate&#39;, function(e){ 
if (history.state){ 
var state = e.state; 
//do something(state.url, state.title); 
} 
}, false);
Copy after login

In this way, you can combine ajax and pushState for perfect browsing without refreshing.
Some restrictions

1. The URL passed must be in the same domain and cannot cross domains

2. Although the state object can store many custom attributes, it cannot be serialized Objects cannot be stored, such as: DOM objects.
Some processing corresponding to the backend

In this mode, in addition to using ajax to browse without refreshing, it is also necessary to ensure that the changed URL can be browsed normally after directly requesting it, so the backend needs to process these. .

1. Send a special header to ajax using pushState, such as: setRequestHeader(‘PJAX’, ‘true’).

2. When the backend obtains the header with PJAX=true, the common parts of the page will not be output. For example: PHP can make the following judgment

function is_pjax(){ 
return array_key_exists(&#39;HTTP_X_PJAX&#39;, $_SERVER) && $_SERVER[&#39;HTTP_X_PJAX&#39;] === &#39;true&#39;; 
}
Copy after login

Although the interface only has pushState, replaceState, and onpopstate, a lot of processing is required when using it.

A plug-in based on jquery has been written for this. The following article will introduce in detail how to use pjax (ajax pushState) to change the URL browsing without refreshing.

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

Related articles:

3-point summary of Ajax technical principles_AJAX related

AJAX encapsulation class usage guide

AJAX Elementary Tutorial: First Introduction to AJAX

The above is the detailed content of Example of using ajax and history.pushState to change the page URL without refreshing_AJAX related. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to change the starting delivery price of Meituan Takeout merchant version How to change the starting delivery price of Meituan Takeout merchant version Mar 27, 2024 pm 07:20 PM

In the operation process of the Meituan Takeout Merchant Edition, the setting of the starting delivery price is a crucial link. A reasonable starting delivery price can not only help merchants control costs, but also increase order amounts to a certain extent, thus increasing overall revenue. However, many merchants don’t know much about how to modify the minimum delivery price. So in the following article, the editor of this website will bring you detailed starting price setting guide for merchants. If you want to know more, come to the following article to find out! In the Meituan Takeout Merchant Center, log in and enter the store settings, then select store management. In the switch navigation at the top of the store management page, select delivery information, and then click Add Delivery Area to complete the operation. Once you add a location, the corresponding shipping costs will automatically appear. After completing your order, you will receive

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

See all articles