pjax 即 pushState + ajax,它被封装成了一个 jQuery 扩展以方便使用。pjax 主要用来解决 HTML 页面局部刷新 url 不更新和不支持后退和前进的问题,提升用户体验。
pjax 的实现是利用 HTML5 的 pushState() 和 replaceState() 新特性和 ajax 结合实现。pushState() 和 replaceState() 用来操作 State(状态)对象,即可添加和修改历史记录,进而更新 url 和提供前进、后退操作 ajax 实现数据的异步加载进而局部刷新。
(下载的附件附有DEMO)
$(document).pjax(selector, [container], options)
参数说明:
selector:是用于单击事件委派的字符串。
container:是一个字符串选择器,用于唯一标识pjax容器。
options:是一个具有如下所述关键点的对象。
key | default | description |
---|---|---|
timeout | 650 | ajax timeout in milliseconds after which a full refresh is forced |
push | true | use pushState to add a browser history entry upon navigation |
replace | false | replace URL without adding browser history entry |
maxCacheLength | 20 | maximum cache size for previous container contents |
version | a string or function returning the current pjax version | |
scrollTo | 0 | vertical position to scroll to after navigation. To avoid changing scroll position, pass false . |
type | "GET" | see $.ajax |
dataType | "html" | see $.ajax |
container | CSS selector for the element where content should be replaced | |
url | link.href | a string or function that returns the URL for the ajax request |
target | link | eventually the relatedTarget value for pjax events |
fragment | CSS selector for the fragment to extract from ajax response |
<a class="leftPaneItem" onclick="writeMail()">写邮件</a>
<div id="control"></div>
function sentMail() {
$.ajax({
url:"./writeMail.html",
success:function (data) {
$("#control").html(data)
}
})
}
/*这里对writeMail.html有些特殊要求,需要在普通html页面的基础上去掉html、meta、body、title等
标签,仅保留body内的部分。如果有引用样式或者脚本可以照常引用,只是路径是相对于发送请求的页面,
而不是被请求的页面。使用pjax插件的话,上面的js就可以改成:*/
function sentMail() {
$.pjax({
url:"./writeMail/writeMail.html",
//请求的页面地址
container:"#control",
//使用什么容器装载html
push:false,
//是否模拟a链接跳转造成的url改变
})
}
/*如果想快速将页面内所有a标签替换成pjax的跳转方式可以写成这样:
$(document).pjax('a', '#container')其中a是触发元素,
#container是装载pjax返回内容的容器。
如果被请求的页面已经包含html、body之类的标签,请求来之后又不想要这些标签,可以这样写:*/
function sentMail() {
$.pjax({
url:"./writeMail/writeMail.html",
//请求的页面地址
container:"#control",
//使用什么容器装载html
push:false,
//是否模拟a链接跳转造成的url改变
fragment:"body"
//css选择器,被选中dom的内容会被抽取出来
})
}
注意:如果使用pjax插件并且在配置里不设置push选项为false,则要求项目内所有经过pjax处理的链接必须采用绝对路径,否则跳转后再次跳转到相对路径则会导致404。
GitHub 地址:https://github.com/defunkt/jquery-pjax