我看到很多網站,例如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