问题 使用AJAX更改div内容 - 如何将导航显示为散列/锚点


我想创建一个刷新div异步内容的页面,同时为用户提供一个锚点,以便能够直接访问div中的内容。 (例如www.website.co.uk/#page1)

我已设法使内容可以更新为1页,但是,如果我添加多个页面,它将停止工作

另外 - 如果我要导航到URL website.co.uk/#page1,它将不会显示#page1。

有人可以帮忙吗?

这是我目前的代码:

HTML:

<h5> <a href="#page1">Test</a></h5>
<h5> <a href="#page2">Test2</a></h5>

JS:

<script type="text/javascript">
    var routes = {
        '#page1' : '{{site.url}}/page1'
        '#page2' : '{{site.url}}/page2'
    };
    var routeHandler = function( event ) {
        var hash = window.location.hash, 
            xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("div1").innerHTML = xhttp.responseText;
            }
        };
        xhttp.open("GET", routes[hash], true);
        xhttp.send();    
    };
    window.addEventListener('hashchange', routeHandler);
    window.addEventListener('load', function() {
        var hash = window.location.hash;
        if (routes.hasOwnProperty(hash)) routehandler();
    });
</script>

5577
2017-07-01 13:10


起源

我在下面添加了Shillys Answer,但是,如果我要直接导航到一个页面(例如www.website.co.uk/#page1),它不会显示所需的内容 - David Smith
你有没有在每条路线后放一个逗号,但最后一个?您在此处显示的路径对象无效,调试器应该告诉您。其他页面的URL是否正确并且是ajax调用返回正确的html? - Shilly


答案:


你犯了一些小js错误。 所以这是你修复的代码

HTML

<h5> <a href="#page1">Test</a></h5>
<h5> <a href="#page2">Test2</a></h5>
<div id="div1"></div>

JavaScript的:

  //change these routs
  var routes = {
    '#page1': '/page1.html',
    '#page2': '/page2.html'
  };

  var routeHandler = function() {

    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
        document.getElementById("div1").innerHTML = xhttp.responseText;
      }
    };

    xhttp.open("GET", routes[window.location.hash], true);
    xhttp.send();

  };

  window.addEventListener('hashchange', routeHandler);
  window.addEventListener('load', function() {
    var hash = window.location.hash;
    if (routes.hasOwnProperty(window.location.hash)) routeHandler();
  });

6
2017-07-08 06:06





您通常使用类似路由器的对象。而不是您正在使用的超链接,将href设置为实际的页面哈希 <a href="#page1">Button Title</a>。然后为窗口对象上的hashchange创建一个事件侦听器,您将在其中获取内容。

最后添加一个您希望能够导航到的网页列表,这样您就可以将“#page1”翻译为实际的网址。

结果是您可以在超链接中使用简单的href,并且当前页面将显示在顶部的URL栏中。

ps:在hashchange侦听器中添加一个未列出路径的检查,因此您仍然可以链接到异地页面。

pps:如果您希望能够直接导航到某个页面,则需要在文档加载时添加对哈希的手动检查。

// html mockup
<a href="#page1">Button Title</a>
// js mockup
var routes = {
    '#page1' : '{{site.url}}/webpage.html'
};

window.addEventListener('hashchange', function( event ) {
    var hash = window.location.hash, // gives you '#page1'
        xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("div1").innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("GET", routes[hash], true);
    xhttp.send();    
});

使用加载侦听器更新:

// html mockup
<a href="#page1">Button Title</a>
// js mockup
var routes = {
    '#page1' : '{{site.url}}/webpage.html'
};
var routeHandler = function( event ) {
    var hash = window.location.hash, // gives you '#page1'
        xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("div1").innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("GET", routes[hash], true);
    xhttp.send();    
};
window.addEventListener('hashchange', routeHandler);
window.addEventListener('load', function() {
    var hash = window.location.hash;
    if (routes.hasOwnProperty(hash)) routehandler();
});

3
2017-07-01 13:24



你比我快。我只是想推荐一下 window.onhashchange 句法。 - mat3e
我更喜欢addEventListener用于所有事件,因此您可以为同一事件添加多个侦听器。如果你使用 window.onhashchange = fn 在应用程序的一个部分中,稍后再次使用它,您将使用object.onsomething语法覆盖第一个侦听器。点击等也是如此。 - Shilly
是的,但我更喜欢在代码中最小化魔术字符串的数量。什么更好,取决于具体情况。 - mat3e
谢谢Shilly - 此代码现在在按下按钮时更改div内容(并显示所需的URL)...但是,如果我导航到提供的URL,它不会在div中显示更新的内容...请你能澄清一下如何做到这一点(抱歉是痛苦的) - David Smith
在考虑之后,我只是部分理解你的意思Mate,并开始想知道使用这种语法有什么缺点。现在我想到了它,我使用了很多魔术字符串来避免对象依赖于彼此。 - Shilly


因为你用jquery标记了这个问题,所以你可以使用jQuery,在这种情况下你可以做类似的事情:

$(window).on('hashchange', refreshContent);

function refreshContent() {
    $.get(getBaseUrl() + location.hash, function(data) {
         $('#div1').html(data);
    });
}

但请注意,那里有更多更复杂的解决方案


2
2017-07-01 13:21





我直接给了 onclick 它的工作。它可能会帮助你。

<h5> <a href="#page1" onclick="test('#page1')">Test</a></h5>
<h5> <a href="#page2" onclick="test('#page2')">Test2</a></h5>
<div id="div1"></div>

<script type="text/javascript">

    var routes = {
        '#page1' : 'page1.html',
        '#page2' : 'page2.html'
    };
    function test(page) {

        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("div1").innerHTML = xhttp.responseText;
            }
        };
        xhttp.open("GET", routes[page], true);
        xhttp.send();    
    }

</script>

我用了 .html 用于检查页面。你用自己的。


2
2017-07-11 08:54