简体   繁体   中英

AJAX/Jquery/PHP - Load page dependant on anchor/hash tag

I have the following code which works great:-

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

Only problem is that I have no idea how to get then read the anchor links I create (eg #contact-us) to create bookmarkable pages.

I tried to do a solution based around the following but it seems less than ideal

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

To get the hash, other than your initial example, you can use window.location.hash

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

You can use replace to get rid of the leading # if required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM