
pJax 页面无刷新跳转
ajax缺点是破坏了浏览器的前进后退,因为ajax的请求不会留在历史记录中。pjax就不一样了,pjax被解释成ajax+pushState的封装,因为它把ajax的请求写入历史记录,并反映在地址栏,这样用户就能愉快地使用前进后退了。pjax有好几个实现方法,这里使用最常用的jQuery库,使用jquery.pjax.js。演示代码的服务器端使用PHP脚本语言。
Pjax用在那儿?就说百度云盘吧,这个大家肯定都用过。百度云盘PC端,在点击打开某个文件夹后会打开这个文件夹下的文件,其实显示文件的这个div就用到了pjax技术。地址栏变换,内容更换,但是却是一个ajax请求。等到后退的时候,不必重新请求上一层文件夹的内容,因为是存在在历史记录中的。而且,开发者还可以选择时候使用cache和storage缓存。
说了这么多,先看下一个小例子,感受下 pjax 的魅力吧:jQuery pjax 页面无刷新跳转在线演示
例1:
客户端:
01 | <!DOCTYPE html> |
02 | < html > |
03 | < head > |
04 | < title >pjax</ title > |
05 | < meta charset = "utf-8" > |
06 | </ head > |
07 | < body > |
08 | < h1 >My Site</ h1 > |
09 | < div > |
10 | Go to < a href = "res1.php" >第一页</ a >.< a href = "res2.php" >第二页</ a > |
11 | </ div > |
12 | < div id = "container" ></ div > |
13 | </ body > |
14 | < script type = "text/javascript" src = "http://www.5imoban.net/download/jquery/jQuery-2.1.1.min.js" ></ script > |
15 | < script type = "text/javascript" src = "http://www.5imoban.net/view/pjax/jquery.pjax-1.8.2.min.js" ></ script > |
16 | < script type = "text/javascript" > |
17 | $(document).pjax('a', '#container') |
18 | </ script > |
19 | </ html > |
服务器端:res1.php
1 | <?php |
2 | echo "<div style='background:red;'>第一页</div>" ; |
3 | res2.php |
4 | <?php |
5 | echo "<div style='background:red;'>第二页</div>" ; |
解释:$(document).pjax('a', '#Container')其中a是触发元素,#container是装载pjax返回内容的容器,下面也是这样。
例2:
客户端:
01 | <!DOCTYPE html> |
02 | < html > |
03 | < head > |
04 | < title >pjax</ title > |
05 | < meta charset = "utf-8" > |
06 | </ head > |
07 | < body > |
08 | < h1 >My Site</ h1 > |
09 | < div > |
10 | < input type = "button" id = "clickMe" value = "GO" > |
11 | </ div > |
12 | < div id = "container" ></ div > |
13 | </ body > |
14 | < script type = "text/javascript" src = "http://www.5imoban.net/download/jquery/jQuery-2.1.1.min.js" ></ script > < script type = "text/javascript" src = "http://www.5imoban.net/view/pjax/jquery.pjax-1.8.2.min.js" ></ script > < script type = "text/javascript" > |
15 | $(function(){ |
16 | $('#clickMe').click(function(){ |
17 | $.pjax({ |
18 | url: './res3.php', |
19 | container: '#container' |
20 | }); |
21 | }); |
22 | }); |
23 | </ script > |
24 | </ html > |
服务器端:res3.php:
1 | <?php |
2 | echo "<div style='background:red;'>第三页</div>" ; |
3 | ?> |
pjax官网:http://pjax.herokuapp.com/