//Gather AJAX links
var ajaxLink = $("#logo, .navLink, .tableLink, .footerLink");
//Mark the recent state as null (because there is none yet)
var recentState = null;
//Initialize the page state based on the URL (bookmarking compatibility)
window.onload = function() {
//If no page state exists, assume the user is at index.html
if (window.location.hash == "") {
window.location.hash = "page=index";
}
//Load the page state based on the URL
loadStateFromURL();
//Keep the page state synchronized (back/forward button compatibility)
setInterval(loadStateFromURL, 500);
//Exit
return;
}
//Use AJAX for certain links
ajaxLink.click(function() {
//Update the URL
window.location.hash = "page=" + $(this).attr("id");
//Load the page state based on the URL
loadStateFromURL();
//Return false or else page will refresh
return false;
});
//Load the page state based on the URL
function loadStateFromURL() {
//If nothing has changed, exit
if (window.location.hash == recentState) {
return;
}
//Mark the recent state
recentState = window.location.hash;
//Go through an array of all AJAX links and check their IDs
for (var i = 0; i < ajaxLink.length; i++) {
//If we find a link's ID that matches the current state, load the relevant content
if ("#page=" + ajaxLink[i].id == window.location.hash) {
//Load contents into article.main
$("article.main").fadeOut(0).load(ajaxLink[i].href, function(response, status, xhr) {
//Show an error if the request fails
if (status == "error") {
$("article.main").load("./404.html");
window.location.hash = "page=404";
}
}).fadeIn(500);
//Update the page title
document.title = "\u2622 My Website Name \u2622 " + ajaxLink[i].text;
document.getElementById("headH2").textContent = ajaxLink[i].text;
//State has been fixed, exit
return;
}
}
}
當我在本地運行它時,此代碼完美地工作!AJAX和setInterval for window.location.hash
但是,當我把它放在網絡服務器上時,當我第一次訪問時,我的AJAX鏈接將刷新頁面。但是,如果我使用後退按鈕,然後再次嘗試鏈接(或者我假設頁面已經在瀏覽器緩存中),它將正常工作。
我不能這樣做,因爲當人們第一次訪問我的頁面時,他們點擊的第一個鏈接將無法按預期運行。
我也一直在測試的一件事是我會用麪包屑書籤(example.com/#page=14)爲我自己的網站添加書籤,並查看它是否在我的頁面不在瀏覽器緩存中時更新。同樣,它在我的本地機器上工作,但不在我的Web服務器上。
仍然沒有,但是我通過.preventDefault文檔閱讀,我很困惑爲什麼.preventDefault不工作,它應該! – katamari 2014-09-29 06:54:58
您是否嘗試過在loadStateFromURL()函數內使用'return false'而不是'return'? – 2014-09-29 06:58:51
我很感激你幫助我。我在每個'return'中交替使用'return false',然後在'return'中嘗試了它,但仍然沒有任何結果。 – katamari 2014-09-29 07:17:36