Question

suppose: i click 1.php then 2.php then 3.php then press back but it does not go to 2.php also url is not effected. I want to change url and support for back also, so it can be SEO friendly here is my code:

<pre>
<html>
<head>
    <script type="text/javascript">
        function show(addr) {
            a = new XMLHttpRequest();
            a.onreadystatechange = function() {
                if (a.readyState==4 && a.status==200) {
                    document.getElementById("content").innerHTML=a.responseText;
                }
            }
            a.open("GET",addr+".php",true); 
            a.send(); //
        }
    </script>
</head>
<body>
    <a href="#" onClick="show('1')">Load 1.php into content</a>
    <a href="#" onClick="show('2')">Load 2.php into content</a>
    <a href="#" onClick="show('3')">Load 3.php into content</a>
    <a href="#" onClick="show('4')">Load 4.php into content</a>

    <!-- Load content here-->
    <div id="content"></div>        
</body>
</html>
</pre>
Was it helpful?

Solution

Even if your anchors have unique tag names, when you navigate through browser history and go back to that particular anchor, it's not going to execute the javascript associated with the onClick of that anchor.

You need to set window.onhashchange to call your show function. You don't even need onclick after the change. I've tested the follow:

    <pre>
    <html>
    <head>
        <script type="text/javascript">
            window.onhashchange=window.onload=function(){
                window.setTimeout(doHashCheck, 10);
            }

            var doHashCheck = (function(global) {
                return function() {
                    var addr = window.location.hash.replace(/^#/,'');
                    show(addr);
                }
            })(this);
            function show(addr)
            {
                a=new XMLHttpRequest();
                a.onreadystatechange=function()
                {
                    if (a.readyState==4 && a.status==200)
                    {
                        document.getElementById("content").innerHTML=a.responseText;
                    }
                }
                a.open("GET",addr+".php",true);
                a.send(); //
            }




        </script>

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache" />
    <META HTTP-EQUIV="Expires" CONTENT="-1" />
    <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, no-store, must-revalidate" />

    </head>
    <a href="#1">Load 1.php into content</a>
    <a href="#2">Load 2.php into content</a>
    <a href="#3">Load 3.php into content</a>
    <a href="#4">Load 4.php into content</a>

    <!-- Load content here-->
    <div id="content"></div>
    </body>
    </html>
    </pre>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top