实现Web 2.0导航系统的最佳方式

时间:2010-07-14 23:11:15

标签: php javascript url cookies address-bar

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

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

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

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

2 个答案:

答案 0 :(得分:3)

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

您的网址应指向真实网页,以使其适用于禁用js的用户。点击处理程序应该处理ajax请求。哈希应该包含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;

}

答案 1 :(得分:0)

我可以看到为什么你可能想用ajax加载页面的部分。整整一页虽然毫无意义。

jQuery解决方案可能类似于:

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

我没有测试过,但它仍然可以在没有启用javascript的情况下运行。