pushState是一个可以操作history的api
pjax是对ajax + pushState的封装,让你可以很方便的使用pushState技术。
同时支持了缓存和本地存储,下次访问的时候直接读取本地数据,无需在次访问。
并且展现方式支持动画技术,可以使用系统自带的动画方式,也可以自定义动画展现方式。
pjax options
$.pjax.click
if ($.support.pjax) {
$(document).on('click', 'a[data-pjax]', function(event) {
var container = $(this).closest('[data-pjax-container]')
var containerSelector = '#' + container.id
$.pjax.click(event, {container: containerSelector})
})
}
$.pjax.submit
$(document).on('submit', 'form[data-pjax]', function(event) {
$.pjax.submit(event, '#pjax-container')
})
$.pjax.reload
$.pjax.reload('#pjax-container', options)
$.pjax
function applyFilters() {
var url = urlForFilters()
$.pjax({url: url, container: '#pjax-container'})
}
Events
event | cancel | arguments | notes |
---|---|---|---|
event lifecycle upon following a pjaxed link | |||
pjax:click | ✔︎ | options | fires from a link that got activated; cancel to prevent pjax |
pjax:beforeSend | ✔︎ | xhr, options | can set XHR headers |
pjax:start | xhr, options | ||
pjax:send | xhr, options | ||
pjax:clicked | options | fires after pjax has started from a link that got clicked | |
pjax:beforeReplace | contents, options | before replacing HTML with content loaded from the server | |
pjax:success | data, status, xhr, options | after replacing HTML content loaded from the server | |
pjax:timeout | ✔︎ | xhr, options | fires after options.timeout ; will hard refresh unless canceled |
pjax:error | ✔︎ | xhr, textStatus, error, options | on ajax error; will hard refresh unless canceled |
pjax:complete | xhr, textStatus, options | always fires after ajax, regardless of result | |
pjax:end | xhr, options | ||
event lifecycle on browser Back/Forward navigation | |||
pjax:popstate | event direction property: "back"/"forward" | ||
pjax:start | null, options | before replacing content | |
pjax:beforeReplace | contents, options | right before replacing HTML with content from cache | |
pjax:end | null, options | after replacing content |
详细文档: https://github.com/defunkt/jquery-pjax
Jquery 版本使用案例: (不能绑定外域的url)
<!DOCTYPE html>
<html>
<head>
<title>pjax</title>
<meta charset="utf-8">
</head>
<body>
<h1>My Site</h1>
<ul>
<li><a href="aliens.data.php">第一页</a></li>
<li><a href="home.data.php">第二页</a></li>
<li><a href="dinosaur.data.php">第三页</a></li>
</ul>
<input type="button" id="clickMe" value="GO">
<div id="container">
<li>1</li>
<li>1</li>
<li>1</li>
</div>
</body>
<script src="jquery-2.2.0.min.js"></script>
<script src="jquery.pjax.js"></script>
<script type="text/javascript">
$(document).pjax('a', '#container');
$( ':button' ).click( function(){
$(document).on('pjax:send', function() {
console.log( 'pjax start' );
})
$(document).on('pjax:complete', function() {
console.log( 'pjax end' );
})
$.pjax({
url: 'ajax.data.php',
container: '#container'
})
});
</script>
</html>
Hoem..data.php
<?php
echo '这是首页啊!';
Aliens.data.php
<?php
echo '这是啊0! 不知道';
Dinosaur.data.php
<?php
echo '这是啊1! 知道了';
Ajax.data.php
<?php
echo '这是Pjax 异步获取数据呢!';