如何在刷新网页时保留当前的页码


How to retain current current pagination page number when webpage is refreshed?

我的主页中包含了简单的分页,以便显示服务器上的最新新闻/图像。分页工作正常,但当我尝试移动到其他页码(例如第2页)时,页面会加载,但刷新后会再次返回到第1页。我是PHP、Ajax和Jquery的新手,所以我不知道在哪里解决这个问题。这是我的代码:

pagination.php

    <?php
function paginate($reload, $page, $tpages, $adjacents) {
$prevlabel = "&lsaquo; Prev";
$nextlabel = "Next &rsaquo;";
$out = '<div class="pagin page_style">';
// previous label
if($page==1) {
    $out.= "<span>$prevlabel</span>";
} else if($page==2) {
    $out.= "<a href='javascript:void(0);' onclick='load(1)'>$prevlabel</a>";
}else {
    $out.= "<a href='javascript:void(0);' onclick='load(".($page-1).")'>$prevlabel</a>";
}   
// first label
if($page>($adjacents+1)) {
    $out.= "<a href='javascript:void(0);' onclick='load(1)'>1</a>";
}
// interval
if($page>($adjacents+2)) {
    $out.= "...'n";
}
// pages
$pmin = ($page>$adjacents) ? ($page-$adjacents) : 1;
$pmax = ($page<($tpages-$adjacents)) ? ($page+$adjacents) : $tpages;
for($i=$pmin; $i<=$pmax; $i++) {
    if($i==$page) {
        $out.= "<span class='current'>$i</span>";
    }else if($i==1) {
        $out.= "<a href='javascript:void(0);' onclick='load(1)'>$i</a>";
    }else {
        $out.= "<a href='javascript:void(0);' onclick='load(".$i.")'>$i</a>";
    }
}
// interval
if($page<($tpages-$adjacents-1)) {
    $out.= "...'n";
}
// last
if($page<($tpages-$adjacents)) {
    $out.= "<a href='javascript:void(0);' onclick='load($tpages)'>$tpages</a>";
}
// next
if($page<$tpages) {
    $out.= "<a href='javascript:void(0);' onclick='load(".($page+1).")'>$nextlabel</a>";
}else {
    $out.= "<span>$nextlabel</span>";
}
$out.= "</div>";
return $out;
}
?>

/////////////////////////////////////////

主页.php

        <?php session_start(); ?>
    <?php 
    $action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
    if($action == 'ajax'){
    /* Connect To Database*/
    $dbname = 'banaue.com';
    $link = mysql_connect("localhost","root","") or die("Couldn't make connection.");
    $db = mysql_select_db($dbname, $link) or die("Couldn't select database");
    include 'pagination.php'; //include pagination file
    //pagination variables
    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = 1; //how many records you want to show
    $adjacents  = 5; //gap between pages after number of adjacents
    $offset = ($page - 1) * $per_page;
    //Count the total number of row in your table*/
    $count_query   = mysql_query("SELECT COUNT(title) AS numrows FROM news");
    $row     = mysql_fetch_array($count_query);
    $numrows = $row['numrows'];
    $total_pages = ceil($numrows/$per_page);
    $reload = 'Home.php';
    //main query to fetch the data
    $result = mysql_query("SELECT * FROM news ORDER BY date_posted LIMIT $offset,$per_page");
    //loop through fetched data
while($test = mysql_fetch_array($result)){
    $id = $test['title'];   
    echo "<div class='content' stye=margin-bottom: 20px;>";
    echo'<div class="img_content" ><img src='.$test['img_path'].' style=height:520px;width:100%;></div>';
                echo"<p class=para_news2 style=margin-left:10px;><font color='#336699'>" .$test['title']."</p></font><br /><br />";
                echo"<p class=para_news4 style=margin-left:10px;width:100%;><img src='images/user.gif'>&nbspStory By: <font color='lavander'>" .$test['author']."</font></p>";
                echo"<p class=para_news4 style=margin-left:10px;width:100%;><img src='images/calendar.gif'>&nbspDate Posted: <font color='red'>". $test['date_posted']. "</font></p>";
                echo"<p class=para_news3 style=margin-left:10px;width:100%;><img src='images/comments.gif'>&nbsp<font color='black'>". $test['intro']. "</font></p><br>";
                echo"<a href ='news.php?title=$id'><font style='float:right;margin-right:10px;background:url(images/bg_header.jpg);padding:2px;'>Read more ...</a><br>";
    echo        "</div>";
}
echo paginate($reload, $page, $total_pages, $adjacents);
} else{
?>
<!DOCTYPE html>
<head><!-- Head declaration -->
<script type="text/javascript">
    $(document).ready(function(){
        load(1);
    });
    function load(page){
        $("#loader").fadeIn('slow');
        $.ajax({
            url:'Home.php?action=ajax&page='+page,
            success:function(data){
                $(".outer_div").html(data).fadeIn('slow');
                $("#loader").fadeOut('slow');
            }
        })
    }
</script>
</head>
<body>
<!-- Body Content -->
<div class="main_body" style="height:auto;">
<!-- Top Stories Query-->
<div class="outer_div">
</div>
</div>
</body>
</html>
<?php }?>

请帮我解决这个问题,这样我就可以继续前进了…

您可以使用cookie将当前分页位置存储在客户端web浏览器中,并在创建页面时将其读回,以从最后一个位置开始分页。

像这样的

setcookie('pagination_pos',$pagination_pos,time() + 86400); // 86400 = expire after 1 day

然后读回

echo 'Current position '($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 0);

这将从cookie中读取当前位置,如果没有cookie,则返回到0。

好吧,正如你要求如何在你的代码中使用它一样,我做了一个简单的示例函数,你可以在代码中使用:

function getPaginationPos(){
if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
    setcookie('pagination_pos',$_REQUEST['page'],time() + 86400);
    return $_REQUEST['page'];
} else {
    return ($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 1);
}
}

这将检查请求中是否有"page"变量,如果有,它将把位置存储为cookie。如果请求中没有"page"变量,它将检查是否有cookie或返回1。

如果我理解你的代码,你必须更换这条

$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;

带有

$page = getPaginationPos();

我在javascript"load"函数中看到了另一个问题,即强制页面1重新加载

$(document).ready(function(){
    load(1);
});

你可以试试这个:

 $(document).ready(function(){
    load();
});

在javascript函数中添加一个page变量的检查,以便在没有设置page的情况下处理这种情况。

    <script type="text/javascript">
      $( document ).ready(function() {
         load()
      });
      function load(page){
      if (typeof page === 'undefined') {
        page = ''
      } else{
        page = '&page='+page
      }
      $("#loader").fadeIn('slow');
      $.ajax({
        url:'Home.php?action=ajax'+page,
        success:function(data){
        $(".outer_div").html(data).fadeIn('slow');
        $("#loader").fadeOut('slow');
        }
      })
      }
    </script>

基于Sir Manuel的代码,如果您不想将变量存储在cookie中,可以尝试将其放入会话变量中。

更改此行:

function getPaginationPos(){
     if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){
          setcookie('pagination_pos',$_REQUEST['page'],time() + 86400);
          return $_REQUEST['page'];
     } else {
          return ($_COOKIE['pagination_pos']!='' ? $_COOKIE['pagination_pos'] : 1);
     }
}

进入这个:

function getPaginationPos(){
    if (isset($_REQUEST['page']) && !empty($_REQUEST['page'])){         
        $_SESSION['pages'] = $_REQUEST['page'];
        return $_REQUEST['page'];
    } else {
        return $_SESSION['pages'];
    }
}

这个:

$(document).ready(function(){
    load();
});

进入这个:

 $(document).ready(function(){
      load(<?php print $_SESSION['pages']; ?>);
 });