我看到 Lifehacker 能够在使用 AJAX 更新部分页面时更改 url。我猜这可以使用 HTML5 或 history.js 插件来实现,但我猜 lifehacker 两者都没有使用。
有没有人知道他们是如何做到的?我是 AJAX 新手,只是设法使用 Ajax 更新了部分页面。
感谢@Robin Anderson 提供详细的分步算法。我试过了,它工作正常。但是,在我可以在生产中测试它之前,我想由你运行我拥有的代码。我做对了吗?
<script type="text/javascript">
var httpRequest;
var globalurl;
function makeRequest(url) {
globalurl = url;
/* my custom script that retrieves original page without formatting (just data, no templates) */
finalurl = '/content.php?fname=' + url ;
if(window.XMLHttpRequest){httpRequest=new XMLHttpRequest}else if(window.ActiveXObject){try{httpRequest=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{httpRequest=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}
/* if no html5 support, just load the page without ajax*/
if (!(httpRequest && window.history && window.history.pushState)) {
document.href = url;
return false;
}
httpRequest.onreadystatechange = alertContents;
alert(finalurl); /* to make sure, content is being retrieved from ajax */
httpRequest.open('GET', finalurl);
httpRequest.send();
}
/* for support to back button and forward button in browser */
window.onpopstate = function(event) {
if (event.state !== null) {
document.getElementById("ajright").innerHTML = event.state.data;
} else {
document.location.href = globalurl;
return false;
};
};
/* display content in div */
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var stateObj = { data: httpRequest.responseText};
history.pushState(stateObj, "", globalurl);
document.getElementById("ajright").innerHTML = httpRequest.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
</script>
PS:我不知道如何在评论中粘贴代码,所以我在这里添加了它。