PJAX (PushState + AJAX) is a refresh-free page loading technology that can achieve smooth page switching and local content updates in the website. The following is a brief introduction on how to use PJAX technology to achieve refresh-free loading of the website:
Introduce PJAX library: First, introduce PJAX library into your website, such as pjax.js or use jQuery pjax plug-in, etc. Make sure these libraries are included when the page loads.
Set PJAX behavior for links: For links that require PJAX, identify them by adding a specific class name or attribute. For example, you could add
pjax-linkclass name ordata-pjaxproperty.<a href="/page1" class="pjax-link">页面1</a> <a href="/page2" data-pjax="/container">页面2</a>- Listen to PJAX events: In JavaScript, listen to PJAX-related events to handle operations such as page loading and content updates.
$(document).on('pjax:send', function() { // 在页面开始加载时的操作,例如显示加载动画或提示 }); $(document).on('pjax:complete', function() { // 当页面加载完成后的操作,例如隐藏加载动画或提示 }); $(document).on('pjax:success', function(event, data) { // 当页面加载成功后的操作,可以获取新内容并将其更新到指定容器 var container = $(this).data('pjax') || '#container'; // 默认更新到指定容器,例如 id 为 "container" 的元素 $(container).html(data); // 将新内容更新到容器中 }); - Initialize PJAX: After the page has finished loading, initialize PJAX as needed.
$(document).ready(function() { // 初始化 PJAX $(document).pjax('.pjax-link', '#container'); });
here .pjax-link is the link selector,#container Is the target container for content updates. You can modify the selector and target container according to actual needs.
The above is a simple PJAX implementation example, the specific implementation may vary according to different PJAX libraries or plug-ins. You can configure and customize it according to the PJAX library documentation and your project needs.
Please note that when using PJAX technology, you must ensure that the server can handle PJAX requests and return the correct responses. The PJAX protocol relies on the PushState API to update the browser's URL; therefore, it is also necessary to handle the browser's "前进" and "后退" navigation actions.
I hope this helps! Wishing you success in implementing the PJAX functionality!