2012-02-10 63 views
1

我有下面的代码的伟大工程: -AJAX/jQuery的/ PHP - 加载页面依赖于锚点/哈希标签

$('.ajax a').click(function() { 
    getpageajax(this.href); 
    return false; 
}); 

function getpageajax(getpage) { 
    if(getpage == "") { 
     //SET ERROR? 
     document.getElementById("main").innerHTML = ""; 
     return; 
    } 
    if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp = new XMLHttpRequest(); 
    } else {// code for IE6, IE5 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange = function() { 
     if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      document.getElementById("main").innerHTML = xmlhttp.responseText; 
     } 
    } 
    var urlarray = getpage.split('/'); 
    location.hash = urlarray[urlarray.length-1]; 
    xmlhttp.open("GET", "includes/AJAXgetpage.php?getpage=" + getpage, true); 
    xmlhttp.send(); 
}; 

唯一的问题是我不知道怎么去然后读取锚链接我创建(例如#contact-us)来创建可收藏的页面。

我试图做基于围绕以下内容的解决方案,但它似乎不太理想

<script> 
var query = location.href.split('#'); 
document.cookies = 'anchor=' + query[1]; 
<?php if (!$_COOKIE['anchor']) : ?> 
window.location.reload(); 
<?php endif; ?> 
<?php 
echo $_COOKIE['anchor']; 
?> 

回答

1

要获得哈希值,比你最初的例子外,你可以使用window.location.hash

// example url - http://www.mysite.com/blog/post#comments 
var hash = window.location.hash; // = "#comments" 

你如果需要,可以使用replace摆脱领先的#

+0

当然,我只需要将锚点传递给我已有的函数。 – 2012-02-10 15:52:32

+0

在移动浏览器上不能再次使用。包括铬... – monymirza 2013-11-20 14:56:02