2012-02-10 38 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