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

时间:2014-04-24 10:44:58

标签: php jquery ajax pagination

我的主页中包含简单的分页,以便从我的服务器显示最新的新闻/图像。分页工作正常,但是当我尝试移动到其他页码示例页面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;
}
?>

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

Home.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 }?>

请帮助我解决这个问题,以便继续......

2 个答案:

答案 0 :(得分:0)

您可以使用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);
}

}

这将检查是否有&#34;页面&#34;请求中的变量,如果是,则将位置存储为cookie。如果没有&#34;页面&#34;变量在请求中,它将检查是否有cookie或返回1.

如果我理解你的代码,你必须替换这一行

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

$page = getPaginationPos();

我在javascript中看到另一个问题&#34; load&#34;在重新加载时强制第1页的功能

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

你可以试试这个:

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

还要将页面变量检查添加到javascript函数中,以便在未设置页面的情况下处理该情况。

    <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>

答案 1 :(得分:0)

基于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']; ?>);
 });