2

一旦 url 由 window.pushState 更新,我的网站不会在刷新页面时加载。我的网站保存在这个位置:http://localhost/ajax.test/index.html 但是在单击带有 href="1" 的链接后,url 更改为 http://localhost/ajax.test/1 .. 这里是源代码:

html:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="myscript.js"></script>

    </head>
    <body>
        <ul>
            <li class="list" id="1"><a href="1">home</a></li>
            <li class="list" id="2"><a href="2">project</a></li>
            <li class="list" id="3"><a href="3">about</a></li>
        </ul>
        <div id="dynamic"></div>
    </body>
</html>

jQuery:

var url = 0;
var state=0;
$(document).ready(function(){
            $('ul a').click(function(e) {
                e.preventDefault();
                alert(e.target);
                url = $(this).attr("href");
                history.pushState({page:url}, url,url);
                loadContent(url);

            });
        });

$(window).bind('popstate', function(e){
    state = event.state;
    if(state){
        loadContent(state.page);
    }else{
        loadContent("home");
    }
    });

    function loadContent(currentPage){
        alert(currentPage);
            $.ajax({
                type: "GET",
                url: "ajax.php",
                data: "id="+currentPage,
                success: function(data){
                    $('#dynamic').html(data);
                    }
                });

        };

php:

<?php
$response = $_GET['id'];
    if($response=="1")
        {
            echo "<h1>You loaded HOME</h1>";
        }
    else if($response=="2")
        {
            echo "<h1>You loaded PROJECT</h1>";
        }
    else if($response=="3")
        {
            echo "<h1>You loaded ABOUT</h1>";
        }
?>
4

0 回答 0