Home >Web Front-end >JS Tutorial >jQuery pjax simple example summary
pjax is a jQuery plugin that uses ajax and pushState to achieve a fast browsing experience, including real permalinks, page titles, and working back buttons. This article mainly shares with you a summary of jQuery pjax simple examples, hoping to help everyone.
The disadvantage of ajax is that it destroys the browser's forward and backward movement, because ajax requests will not stay in the history. Pjax is different. Pjax is interpreted as a package of ajax+pushState, because it writes ajax requests into the history and reflects them in the address bar, so that users can happily use forward and backward. There are several implementation methods for pjax. The most commonly used jQuery library is used here, using jquery.pjax.js. The server side of the demo code uses the PHP scripting language.
Where is Pjax used? Let’s talk about Baidu Cloud Disk, everyone must have used this. On the PC side of Baidu Cloud Disk, when you click to open a folder, the file in the folder will be opened. In fact, the p that displays the file uses pjax technology. The address bar changes and the content changes, but it is an ajax request. When you go back, you don't have to re-request the contents of the upper-level folder because it exists in the history. Moreover, developers can also choose to use cache and storage caching.
Example 1,
<!DOCTYPE html> <html> <head> <title>pjax</title> <meta charset="utf-8"> </head> <body> <h1>My Site</h1> <p> Go to <a href="res1.php" rel="external nofollow" >第一页</a>.<a href="res2.php" rel="external nofollow" >第二页</a> </p> <p id="container"></p> </body> <script src="../jquery-2.1.4.min.js"></script> <script src="../jquery.pjax.js"></script> <script type="text/javascript"> $(document).pjax('a', '#container') </script> </html>
res1.php
<?php echo "<p style='background:red;'>第一页</p>";
res2.php
<?php echo "<p style='background:red;'>第二页</p>";
Explanation:
$(document).pjax('a', '#Container')
where a is the trigger element, # container is the container that loads the content returned by pjax, and the same is true below.
Example 2,
<!DOCTYPE html> <html> <head> <title>pjax</title> <meta charset="utf-8"> </head> <body> <h1>My Site</h1> <p> <input type="button" id="clickMe" value="GO"> </p> <p id="container"></p> </body> <script src="../jquery-2.1.4.min.js"></script> <script src="../jquery.pjax.js"></script> <script type="text/javascript"> $(function(){ $('#clickMe').click(function(){ $.pjax({ url: './res3.php', container: '#container' }); }); }); </script> </html>
Server-side code:
res3.php:
<?php echo "<p style='background:red;'>第三页</p>";
Three comprehensive applications
window.history.pushState(state, title, url);
// https://developer.mozilla.org/zh- CN/docs/Web/API/History/pushState
// @State object: Additional object that records historical points, can be empty.
// @Page title: Currently not supported by all browsers.
// @Optional URL: The browser will not check whether the URL exists, only change the URL. The URL must be in the same domain and cannot cross domains.
PJAX is actually HTML5 window.history.pushState (state, title, url) This new API plus traditional AJAX technology is generally used to achieve page loading without refreshing. The main function of pushState is to change the URL and add return history. In this way, after AJAX loads the page without refreshing, the user You can also go back and forward normally, and JS's window.history.back() and window.history.forward() can also work normally. The following is a page loading without refreshing using pushState + jQuery AJAX. Browsing is not supported. The server will automatically degrade to the original link opening form.
index.php:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Index</title> <script src="jquery.js"></script> </head> <body> <p id="main"> <a href="data.php" rel="external nofollow" >data.php</a> <script> $(document).ready(function() { $('#main').on('click','a',function(e) { if(window.history.pushState) { e.preventDefault(); //不跟随原链接跳转 url = $(this).attr('href'); $.ajax({ async: true, type: 'GET', url: 'data.php', data: 'pjax=1', success: function(data) { window.history.pushState(null, null, url); //改变URL和添加返回历史 document.title = data.title; //设置标题 $('#main').html(data.main); //设置内容 } }); } else { return; //低版本IE8等不支持HTML5 pushState,直接返回进行链接跳转 } }); }); </script> </p> </body> </html>
data.php:
<?php if(isset($_GET['pjax'])) { //PJAX请求返回JSON $arr['title'] = 'Data'; $arr['main'] = '<h1>Data Content</h1>'; //下面这两句是把PHP数组转成JSON对象返回 header('Content-Type: application/json; charset=utf-8'); echo json_encode($arr); } else { //常规请求返回HTML ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Data</title> <script src="jquery.js"></script> </head> <body> <p id="main"><h1>Data Content</h1></p> </body> </html> <?php } ?>
Note that the JS statistics code should be placed in the main block to properly count the number of page visits.
Example 2:
<p class="body"> <?php $action_name = $Think.ACTION_NAME; ?> <!-- 头部哟 --> <?php if ($action_name == 'news'): ?> <include file="Brand:header_news" /> <?php elseif ($action_name == 'forum'): ?> <include file="Brand:header_forum" /> <?php endif; ?> <!-- 资讯的二级分类 --> <p class="cb"></p> <p class="brand-news-nav pjax"> <ul class="clearfix"> <li <?php if($_GET['cat'] == '') echo 'class="selected"'; ?>><a class="first" href="{:U("Brand/$action_name")}">全部</a></li> <volist name="cat_list" id="vo" key="i"> <li <?php if($_GET['cat'] == $vo['id']) echo 'class="selected"'; ?>><a href="{:U("Brand/$action_name",array('cat'=>$vo['id']))}">{$vo.name}</a></li> </volist> </ul> </p> <script type="text/javascript"> $(function(){ $(document).pjax('.pjax a', '#pjax-container',{ type:'post', scrollTo:false, }); $(document).on('pjax:click', function() { enable_loading = false; }) $(document).on('pjax:send', function(){ var str = "<p class='tc mt-10'>加载中...</p>"; $('#pjax-container').html(str); }) //最后一个右侧加边框 $(".brand-news-nav ul li").last().children('a').addClass('last'); $(".brand-news-nav ul li").click(function(){ $(this).addClass('selected').siblings().removeClass('selected'); }) }) </script> <!-- 文章列表页 --> <p class="wrap clearfix"> <p class="brand-news-list fl" id="pjax-container"> <include file="Brand:article_pjax" /> </p> <p class="brand-news-right fr pb-20"> <a href="{$adv3[0]['url']}"><img class="scrollLoading" data-url="{$adv3[0]['images']|showImagePath}" src="__PUBLIC__/index/images/loading270x160.gif" width="260" height="150"></a> <p class="title mt-10">法律支持</p> <ul class="bgc-fff"> <volist name="law_list" id="vo"> <a href="{:U('law',array('id'=>$vo['id']))}"><li>{$vo.name}</li></a> </volist> </ul> <button class="btn btn-right mt-10 btn-consult">免费咨询</button> <script type="text/javascript"> $(function(){ //最后一个需要添加一个last的样式 $(".brand-news-right li:last").addClass('last'); }) </script> </p> </p> </p>
Server-side code
if(is_pjax()){ $this->display('article_pjax'); }else{ $this->display('article'); }
//判断是否是pjax请求 function is_pjax(){ return array_key_exists('HTTP_X_PJAX', $_SERVER) && $_SERVER['HTTP_X_PJAX']; }
The main idea is that when .pjax a is clicked, #pjax-container The content is replaced with the requested content. During back-end processing, it is necessary to determine whether it is a pjax request. If it is a partial rendering, if not all rendering is required.
Because pjax uses HTML5 technology, if the browser does not support Html5, the website will jump load normally. If it supports it, it will only perform partial rendering (but the url in the browser address bar will Normally follow the a link to make changes).
Note that in the above js code, there is a parameter scrollTo:false when configuring pjax. Adding this parameter means that the scrollBar of the web page will not change after clicking the connection. Without this parameter, every time you click The browsing window will automatically jump to the top of the web page
Summary: Pjax actually returns a code snippet from the server without refreshing the page, and at the same time modifies the url address, which can save resource loading and improve page loading. speed.
Attachment: pjax’s github project addresshttps://github.com/defunkt/jquery-pjax
Related recommendations:
Navigation bar PJAX refresh problem
The above is the detailed content of jQuery pjax simple example summary. For more information, please follow other related articles on the PHP Chinese website!