Pergunta

Suponha: clique em 1.php e depois 2.php e depois 3.php e pressione novamente, mas ele não vai para 2.php também o URL também não é efetuado. Quero mudar de URL e suporte para voltar também, para que possa ser amigável para SEO aqui está o meu código:

<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>
Foi útil?

Solução

Mesmo que suas âncoras tenham nomes de tags exclusivos, quando você navega pela história do navegador e volta a essa âncora em particular, ela não executará o JavaScript associado ao OnClick dessa âncora.

Você precisa definir o Window.onhashchange para chamar sua função de show. Você nem precisa de OnClick após a mudança. Eu testei o seguinte:

    <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>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top