Best way to implement a Web 2.0 navigation system

折月煮酒 提交于 2019-12-04 20:49:17

There was a similar question not so long ago, and I came up with the following solution.

Your urls should point to real pages in order to get it work in for js disabled users. The click handlers should handle ajax requests. Hash should contain the url, and a part like &ajax to indicate the type of the request.

If the request is from ajax simply send the content. If it is not, wrap the content into header and footer to respond with a full site.

Urls should work with linking to ajax generated hashes and using them as links. The whole idea is basically mimics the kind of behavior you can see on 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"  

prepend

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

append

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

}

I can see why you might want to load parts of the page with ajax. A whole page is rather pointless though.

A jQuery solution might be something like:

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

I have in no way tested that, but it should still work without javascript enabled.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!