window.location.hash的AJAX和setInterval

时间:2014-09-29 06:07:59

标签: javascript jquery ajax setinterval window.location

//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链接会在我第一次访问时刷新页面。但是,如果我使用后退按钮然后再次尝试链接(或者我假设页面已经在浏览器缓存中),它将正常工作。

我不能允许这样做,因为当人们第一次访问我的页面时,他们点击的第一个链接将无法按预期运行。

我一直在测试的其中一件事是我会使用痕迹书签(example.com/#page=14)为我自己的网站添加书签,看看它是否更新,而我的页面已经不在浏览器缓存中。同样,它可以在我的本地计算机上运行,​​但不能在我的Web服务器上运行。

3 个答案:

答案 0 :(得分:0)

使用event.preventDefault()

ajaxLink.click(function(e) {
    e.preventDefault();

    //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;
});

答案 1 :(得分:0)

问题可能是当您将点击事件应用于这些链接时,它们可能无法加载到DOM。因此,可能的解决方案是将ajaxLink.click(function() { ... });部分放在window.load事件或document.ready事件中。由于您已经使用了window.load事件,因此可以执行以下操作。

//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);

    //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;
    });

    //Exit
    return;
  }

答案 2 :(得分:0)

解决了我自己的问题,不得不连续解析AJAX链接,以便在DOM发生变化时保持更新。

首先,我将ajaxLink声明放入函数中:

//Gather AJAX links
function parseAjaxLinks() {
    var ajaxLink = $("#logo, .navLink, .tableLink, .footerLink");
    return ajaxLink;
}

然后我必须将ajaxLink点击事件放入一个函数中:

//Load the page state from an AJAX link click event
function loadStateFromClick() {
    //Update the AJAX links
    var ajaxLink = parseAjaxLinks();

    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;
    });
}

然后我在window.onload事件中添加了一行来保持我的AJAX点击事件与DOM同步(这增加了开销,但是很好):

//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";
        recentState = window.location.hash;
    }

    //Load the page state based on the URL
    loadStateFromURL();

    //Keep the page state synchronized (back/forward button compatibility)
    setInterval(loadStateFromURL, 250);

    //Keep AJAX links synchronized (with DOM)
    setInterval(loadStateFromClick, 250);

    //Exit
    return;
}

如果你有敏锐的眼光,你看到我在我的新loadStateFromClick函数中调用了新的parseAjaxLinks,所以我在loadStateFromURL函数的顶部添加了一行来保持链接更新:

//Load the page state based on the URL
function loadStateFromURL() {
    //Update the AJAX links
    var ajaxLink = parseAjaxLinks();

...

我从中学到的是依赖于DOM的变量需要不断更新。虽然DOM正在加载,但事情是不可预测的,有点糟糕。 **喝啤酒**