日期:2014-05-17  浏览次数:20681 次

HTML5 修改浏览器url而不刷新页面
<?php
if(!isset($_REQUEST['page'])){
$page = 1;
}
else{
$page = intval($_REQUEST['page']);
}

if(isset($_REQUEST['ajaxload'])){
echo "第{$page}页的内容";
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTML5 修改浏览器url而不刷新页面</title>
<script type="text/javascript">
var domLoaded = function(){
if(ua != null && ua[1] < 10){
alert('您的浏览器不支持');
return ;
}

if(location.href.indexOf("?") > -1){
var urlparts = location.href.match(/(.+?)\?.+/i);
var urlbase = urlparts[1];
}
else{
var urlbase = location.href;
}
var page = <?php echo $page;?>;
var ua = window.navigator.userAgent.match(/msie (\d\.\d)/i);
var content = document.getElementById("content");
var loading = document.getElementById("loading");

window.history.replaceState(
{
content:content.innerHTML,
page:page
},
page,
urlbase + (page > 1 ? '?page=' + page : '' )
);

var ajax = new XMLHttpRequest();
var ajaxCallback = function(){
if(ajax.readyState == 4){
loading.style.display = 'none';
content.innerHTML = ajax.responseText;
window.history.pushState(
{
content:content.innerHTML,
page:page
},
page,
urlbase + "?page=" + page
);
next.href = urlbase + "?page=" + (page + 1);
}
};

var next = document.getElementById('next');
var nextClickEvent = function(event){
if(loading.style.display != 'block'){
loading.style.display = 'block';
page++;
ajax.open('GET', urlbase + '?page=' + page + '&ajaxload=on', true);
ajax.onreadystatechange = ajaxCallback;
ajax.send('');
event.preventDefault();
}
};
next.addEventListener('click', nextClickEvent, false);

var popstate = function(){
content.innerHTML = history.state.content;
page = history.state.page;
};
window.addEventListener('popstate', popstate, false);
};

try{
window.addEventListener('DOMContentLoaded', domLoaded, false);
}
catch(e){
alert('您的浏览器不支持');
}
</script>
</head>
<body>
<p id="content">
<?php echo "第{$page}页的内容";?>
</p>
<p>
<a id="next" href="?page=<?php echo $page+1;?>">下一页</a>
</p>
<div id="loading" style="display:none;">
加载中
</div>
</body>
</html>



出处:
http://vifix.cn/blog/html5-modify-browser-url-without-reloading-page.html