ajax加载数据点击返回按钮可以回去

js 发表时间:2016-12-03 作者:七七 浏览次数:851

    

    页面数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax 局部加载</title>
    <style>
        *{
            padding: 0px;
            margin: 0px;
            font-size: 14px;
            background: #dbdbdb;
        }
        li{
            float: left;
            list-style: none;
            height: 50px;
            line-height: 50px;
            width: 33%;
            text-align: center;
            color: #fff;
            font-weight: 800;
        }
        ul{
            overflow: hidden;
        }
        #main{
            width: 80%;
            margin: 50px auto;
            height: 500px;
        }
        #main > div{
            width: 99%;
            height: 300px;
            line-height: 300px;
            background: #333;
            color: #00B2D7;
            font-size: 40px;
            font-weight: 800;
            text-align: center;
        }
    </style>
</head>
<body>

    <div id="main">
        <ul>
            <li style="background: blue;">蓝色</li>
            <li style="background: red;">红色</li>
            <li style="background: green;">绿色</li>
        </ul>
        <div></div>
    </div>

    <!--引入jquery-->
 <script src="http://zqiqi.cn/Public/Home/Mobile/js/jquery-2.1.0.js"></script>
    <script>
        alert(1);
        //设置默认状态
 var defaultName = $('ul li').eq(0).text()
        !location.hash && (location.href = "#name=" + defaultName);
        var val = location.hash.substring(6);
        getContent(val);


        //点击相关按钮改变name值
 $('ul li').click(function () {
            var val = $(this).text();
            var url = "#name=" + val;
            location.href = url;
        })
        
        window.onhashchange = function() {
            var hash = location.hash;
            var val = hash.substring(6);
            getContent(val);
        };

        function getContent(val) {
            $.get("data.php", {name: val}, function(data) {
                $('#main > div').text(data);
            });
        }
    </script>
</body>
</html>

    

    请求的PHP代码

<?php
/**
 * Created by PhpStorm.
 * User: qiqi
 * Date: 2016/12/3
 * Time: 16:06
 */

header("Content-type: text/html; charset=utf-8");
$name = $_GET['name'];
echo $name . '相关数据';