pjax实现无刷新,同时改变url (场景:列表页,查看详情时,返回无刷新回到历史位置)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37462176/article/details/81410665

jQuery的Pjax插件,Pjax即pushState + Ajax,是实现无刷新ajax加载并解决浏览器前进和后退问题的一个开源实现。优于ajax无刷新的是,pjax在实现无刷新更改页面时,同时更改了url。

1,前端页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf8">
    <title>pjax测试</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery.pjax/2.0.1/jquery.pjax.js"></script>

    <style type="text/css">
        .main{border:1px solid red;width: 1000px;height: 500px;margin: 0px auto}
        .click{margin: 0px auto;text-align: middle;width: 1000px;margin-top: 20px;}
    </style>
</head>
<body>
<div class="main" style="text-align: center">1111</div>
<div class="click">
    <button class="red">红色模板</button>
    <button class="green">绿色模板</button>
</div>

<div class="main" style="text-align: center">222</div>
<div class="click">
    <button class="red">红色模板</button>
    <button class="green">绿色模板</button>
</div>

<div class="main" style="text-align: center">333</div>
<div class="click">
    <button class="red">红色模板</button>
    <button class="green">绿色模板</button>
</div>
<script type="text/javascript">
    $('button').bind('click',function(){
        var color=$(this).attr('class');
        $.pjax({
            url: 'change.php?color='+color,
            container: '.main'
        })
    });
</script>
</body>
</html>

2,后端change.php

<?php
$color=$_GET['color'];
if($color) {
    $path = $color . '.html';
    include($path);
}

3,green.html  页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>绿色模板</title>
</head>
<body>
<div id="color" style="background-color:green;width:1000px;height:500px;margin: 0px auto"></div>
</body>
</html>

red.html  页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>红色模板</title>
</head>
<body>
    <div id="color" style="background-color:red;width:1000px;height:500px;margin: 0px auto"></div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_37462176/article/details/81410665