我看到很多网站,例如gitHub更改它的html内容和URL
而不刷新页面。
我找到一种可能的方法在HTML Histroy API
中做到这一点。
这是代码。
HTML更改html内容和网址,无需重新加载页面
<div class="container">
<div class="row">
<ul class="nav navbar-nav">
<li><a href="home.html" class="historyAPI">Home</a></li>
<li><a href="about.html" class="historyAPI">About</a></li>
<li><a href="contact.html" class="historyAPI">Contact</a></li>
</ul>
</div>
<div class="row">
<div class="col-md-6">
<div class="well">
Click on Links above to see history API usage using <code>pushState</code> method.
</div>
</div>
<div class="row">
<div class="jumbotron" id="contentHolder">
<h1>Home!</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
</div>
</div>
</div>
home.html的
This is home page
about.html
This is about page
contact.html
That one is content page
JAVASCRIPT
<script type="text/javascript">
jQuery('document').ready(function(){
jQuery('.historyAPI').on('click', function(e){
e.preventDefault();
var href = $(this).attr('href');
// Getting Content
getContent(href, true);
jQuery('.historyAPI').removeClass('active');
$(this).addClass('active');
});
});
// Adding popstate event listener to handle browser back button
window.addEventListener("popstate", function(e) {
// Get State value using e.state
getContent(location.pathname, false);
});
function getContent(url, addEntry) {
$.get(url)
.done(function(data) {
// Updating Content on Page
$('#contentHolder').html(data);
if(addEntry == true) {
// Add History Entry using pushState
history.pushState(null, null, url);
}
});
}
</script>
此代码工作正常,即使你回去或者在浏览器转发。
但问题是,当你刷新页面时,它只显示正在刷新的文件。例如,如果刷新about.html
,则仅显示以下内容:This is the about page
。与gitHub不同,它不能显示完整的页面。正如你在gitHub
中看到的那样,即使你刷新页面,它也会显示与刷新前相同的页面。
我该怎么做?
谢谢...
如果你想在每次刷新时设置默认页面,那么你可以使用窗口的ajax onload,但不建议这样做,但如果你想要它,你有这个选项 – WisdmLabs
[很好的教程使用HTML5 History API (?pushState的)](HTTP://计算器。com/questions/4015613/good-tutorial-for-using-html5-history-api-pushstate) – Cristik