window.location.hash的AJAX和setInterval

时间:2020-12-25 15:15:29
//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;
        }
    }
}

This code works flawlessly when I run it locally!!!

当我在本地运行时,这段代码完美无缺!

But when I throw it on the web server my AJAX'd links will refresh the page when I first visit. However, if I use the back button then try the link again (or I'm assuming if the page is already in the browser cache), it will work properly.

但是当我把它扔到网络服务器上时,我的AJAX链接会在我第一次访问时刷新页面。但是,如果我使用后退按钮然后再次尝试链接(或者我假设页面已经在浏览器缓存中),它将正常工作。

I cannot allow this, because when people first visit my page the first link they click on will not operate as intended.

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

One of things I've also been testing is I'll bookmark my own site with a breadcrumb bookmark (example.com/#page=14) and see if it updates without my page already being in the browser cache. Again, it works on my local machine but not on my web server.

我一直在测试的一件事是,我将使用面包屑书签(example.com/#page=14)为我自己的网站添加书签,看看它是否更新,而我的页面已经不在浏览器缓存中。同样,它适用于我的本地计算机,但不适用于我的Web服务器。

3 个解决方案

#1


0  

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

#2


0  

The issue maybe is that when you are applying your click event to these links, they may not be loaded to the DOM. So the possible solution is to put ajaxLink.click(function() { ... }); part inside window.load event or document.ready event. Since you have used window.load event, you can do something like this.

问题可能是当您将click事件应用于这些链接时,它们可能无法加载到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;
  }

#3


0  

Solved my own question, had to continuously parse the AJAX links to stay updated with the DOM as it changes.

解决了我自己的问题,不得不不断解析AJAX链接,以便随着DOM的变化保持更新。

First I put the ajaxLink declaration into a function:

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

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

Then I had to put the ajaxLink click events into a function:

然后我不得不将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;
    });
}

Then I added a line in my window.onload event to keep my AJAX click events synchronized with the DOM (this adds overhead, but oh well):

然后我在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;
}

If you have a keen eye, you saw I had called the new parseAjaxLinks in my new loadStateFromClick function, so I added a line to the top of my loadStateFromURL function to keep the links updated in there as well:

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

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

...

What I learned from this is the variables which are dependent on the DOM need to be continuously updated. While the DOM is loading, things are unpredictable and kind of sucks. **Drinks beer**

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

#1


0  

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

#2


0  

The issue maybe is that when you are applying your click event to these links, they may not be loaded to the DOM. So the possible solution is to put ajaxLink.click(function() { ... }); part inside window.load event or document.ready event. Since you have used window.load event, you can do something like this.

问题可能是当您将click事件应用于这些链接时,它们可能无法加载到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;
  }

#3


0  

Solved my own question, had to continuously parse the AJAX links to stay updated with the DOM as it changes.

解决了我自己的问题,不得不不断解析AJAX链接,以便随着DOM的变化保持更新。

First I put the ajaxLink declaration into a function:

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

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

Then I had to put the ajaxLink click events into a function:

然后我不得不将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;
    });
}

Then I added a line in my window.onload event to keep my AJAX click events synchronized with the DOM (this adds overhead, but oh well):

然后我在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;
}

If you have a keen eye, you saw I had called the new parseAjaxLinks in my new loadStateFromClick function, so I added a line to the top of my loadStateFromURL function to keep the links updated in there as well:

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

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

...

What I learned from this is the variables which are dependent on the DOM need to be continuously updated. While the DOM is loading, things are unpredictable and kind of sucks. **Drinks beer**

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