【问题标题】:Best way to implement a Web 2.0 navigation system实现 Web 2.0 导航系统的最佳方式
【发布时间】:2011-03-16 03:24:09
【问题描述】:

现在这是我的情况:我正在制作一个 CMS。单击链接时,我希望页面使用 Ajax 动态加载。链接中的问题!

实时更改地址栏中地址的唯一方法是使用锚标记。但是 PHP 没有得到锚标签,因此我无法使用 PHP 在站点加载时加载页面内容。 如果我要使用查询字符串加载页面,则无法在单击链接时在地址栏中更新查询字符串,因为这会重新加载页面。

我想 Javascript 可以检查地址,将锚标记保存在 cookie 中并重新加载页面,但我宁愿不必如此冗长。

有人知道这个问题的解决方案吗?

【问题讨论】:

    标签: php javascript url cookies address-bar


    【解决方案1】:

    不久前有一个类似的问题,我想出了以下解决方案。

    您的 url 应该指向真实页面,以使其适用于 js 禁用用户。点击处理程序应该处理 ajax 请求。 Hash 应该包含 url,以及像&ajax 这样的部分来指示请求的类型。

    如果请求来自 ajax,只需发送内容。如果不是,则将内容包装到页眉和页脚中以响应整个站点。

    Urls 应该与链接到 ajax 生成的哈希并将它们用作链接一起使用。整个想法基本上是模仿你在 facebook 上看到的那种行为。

    Javascript

    // click handler for ajax links
    function goToWithAjax(hash) {
      hash = hash.href ? hash.getAttribute("href", 2) : hash;
      ajax( hash, function( response ) {
        document.getElementById("content").innerHTML = response;
      });
      hash = ("#!/" + hash).replace("//","/");
      window.location.hash = hash;
      return false;
    }
    

    .htaccess

    auto_prepend_file = "prepend.php"  
    auto_append_file  = "append.php"  
    

    前置

    $url   = $_SERVER['REQUEST_URI'];
    $parts = explode('#!', $url);
    $hash  = isset($parts[1]) ? $parts[1] : false;
    
    // redirect if there is a hash part
    if ($hash) {
      header("Location: $hash");
    }
    
    // find out if it's an ajax request
    $ajax = strstr($url, "&ajax");
    
    // we need header if it's not ajax
    if (!$ajax) {
      get_header();
    }
    

    追加

    // we need footer if it's not ajax
    if (!$ajax) {
      get_footer();
    }
    

    get_header()

    function get_header() {
    
    echo <<< END
    <html>
    <head></head>
    <body>
    <div id="page">
      <div id="header">
        <div id="logo"></div>
        <ul id="nav">menu...</ul>
      </div>
      <div id="content">
    END;
    
    }
    

    get_footer()

    function get_footer() {
    
    echo <<< END
      </div> <!-- end of #content --->
      <div id="footer">(c) me</footer>
    </div> <!-- end of #page --->
    </body>
    </html>
    END;
    
    }
    

    【讨论】:

    • 我支持这个解决方案,这是您在 Facebook 等看到的非常常见的实现。注意 - 如果您想将内容暴露给蜘蛛,请确保您在某个地方有可用的站点地图。跨度>
    • 这些链接都是指向整页的链接。蜘蛛获取内容就像它们在 WEB 1.0 页面中一样。但是,是的,无论如何都需要站点地图。 :)
    • 前置/附加方法不是很强大。用它来构建复杂的站点是很困难的。通过使用 MVC 方法,最好拥有页面的完整版本和页面不同部分的几个可调用部分。
    【解决方案2】:

    我明白为什么您可能希望使用 ajax 加载页面的部分。不过,一整页是毫无意义的。

    jQuery 解决方案可能类似于:

    $(a.ajax_link).click(function(){
      var url = $(this).attr('href');
      $.ajax({
        url:url,
        success:function(data) {
          $('body').html(data);
          return false;
        }
      });
    });
    

    我没有对此进行过测试,但在没有启用 javascript 的情况下它仍然可以工作。

    【讨论】:

    • 这与我的问题完全无关。对不起
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多