更新URL栏

时间:2012-10-22 15:36:14

标签: jquery ajax

  

可能重复:
  How AJAX is done in github source browse?

目前我在链接上有一个div和以下代码:

<a href="#" onclick="$('div#content').load('Admin/users.php');" id="admin-panel-icon"></a>

基本上,只是将文件users.php加载到index.php页面上的div内容中。在URL栏中,在从href =“#”获取的index.php之后添加#just。

所以我现在已经做到了,所以链接如下所示:

<a href="#AdminUsers" onclick="$('div#content').load('Admin/users.php');" id="admin-panel-icon">

但现在存在书签和页面刷新的问题。如何在用户访问index.php#AdminUsers时将其加载到div #Contents中?

我想有可能是我正在做的更好的解决方案。我的意思是理想情况下我希望人们能够访问/Admin/users.php并且没有任何哈希标签,但我不知道我是怎么做的,同时只加载users.php内容?

3 个答案:

答案 0 :(得分:1)

您可以使用:

<a href="#AdminUsers" [...]>

希望有所帮助。

编辑: 您可以在加载时以哈希方式加载网站:

window.onload = function() {
  var l_hash = location.hash;
  if(l_hash.length>1) {
   var pagename = location.hash.substr(1);
   //do something with the pagename, e.g.:
    if(pagename=="AdminPage") {
      $('div#content').load('Admin/users.php');
    }
  }
}

答案 1 :(得分:1)

如果您的网址有哈希值,您需要检查onLoad($(document).ready())。 如果是这样,jQuery应该加载指定的内容。但是你必须以某种方式将'#AdminUsers'链接到'Admin / users.php'。我建议使用隐藏的输入。

首先,创建一个加载ajax内容的函数(而不是直接在链接上执行)

function loadContent(page){
    $('div#content').load(page);
}

并在您的链接中:

<a href="#AdminUsers" onclick="loadContent('Admin/users.php');" id="admin-panel-icon" ></a>

以及某处,每页:

<input type="hidden" name="AdminUsers" id="AdminUsers" value="Admin/users.php" />

请注意,我在href中放置了自定义哈希(AdminUsers)。因此,当用户点击它时,它会将所需的哈希值放在网址上。

最后,在加载时检查哈希的函数:

$(document).ready(function(){
    if(window.location.hash){
        var hash = window.location.hash;
        $target = $('#'+hash.slice(1));
        if ($target.length) {//found the hidden input field with your URL
            loadContent($target.val());
        }
    }
});

如果要在直接访问时显示整页,请执行:(在PHP中):

<?php if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
 strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest'): //not ajax -> display header ?>
<div id="header">
   <!-- header content -->
</div>
<?php endif; ?>

答案 2 :(得分:0)

您可以使用jQuery hashchange插件查看http://benalman.com/projects/jquery-hashchange-plugin/