当前位置: 首页 > 面试题库 >

客户端分页记录

方浩旷
2023-03-14
问题内容

我正在使用php,mysql进行搜索,过滤操作。

我的分页课程是

class Paginator{
var $items_per_page;
var $items_total;
var $current_page;
var $num_pages;
var $mid_range;
var $low;
var $limit;
var $return;
var $default_ipp;
//var $querystring;
var $ipp_array;

function Paginator()
{
    $this->current_page = 1;
    $this->mid_range = 2;
    $this->ipp_array = array(2,4,6,8,10,'All');
    $this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}

function paginate()
{
    if(!isset($this->default_ipp)) $this->default_ipp='2';
    if($_GET['ipp'] == 'All')
    {
        $this->num_pages = 1;
   //$this->items_per_page = $this->default_ipp;
    }
    else
    {
        if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
        $this->num_pages = ceil($this->items_total/$this->items_per_page);
    }
    $this->current_page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1 ; // must be numeric > 0
    $prev_page = $this->current_page-1;
    $next_page = $this->current_page+1;
    if($_GET)
    {
        $args = explode("&",$_SERVER['QUERY_STRING']);
        foreach($args as $arg)
        {
            $keyval = explode("=",$arg);
            if($keyval[0] != "page" And $keyval[0] != "ipp") $this->querystring .= "&" . $arg;
        }
    }

    if($_POST)
    {
        foreach($_POST as $key=>$val)
        {
            if($key != "page" And $key != "ipp") $this->querystring .= "&$key=$val";
        }
    }
    if($this->num_pages > 4)
    {
        $this->return = ($this->current_page > 1 And $this->items_total >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$prev_page&ipp=$this->items_per_page$this->querystring\">&laquo; Previous</a> ":"<span class=\"inactive\" href=\"#\">&laquo; Previous</span> ";

        $this->start_range = $this->current_page - floor($this->mid_range/2);
        $this->end_range = $this->current_page + floor($this->mid_range/2);

        if($this->start_range <= 0)
        {
            $this->end_range += abs($this->start_range)+1;
            $this->start_range = 1;
        }
        if($this->end_range > $this->num_pages)
        {
            $this->start_range -= $this->end_range-$this->num_pages;
            $this->end_range = $this->num_pages;
        }
        $this->range = range($this->start_range,$this->end_range);

        for($i=1;$i<=$this->num_pages;$i++)
        {
            if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
            // loop through all pages. if first, last, or in range, display
            if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range))
            {
                $this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> ";
            }
            if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
        }
        $this->return .= (($this->current_page < $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All') And $this->current_page > 0) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$next_page&ipp=$this->items_per_page$this->querystring\">Next &raquo;</a>\n":"<span class=\"inactive\" href=\"#\">&raquo; Next</span>\n";
        $this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
    }
    else
    {
        for($i=1;$i<=$this->num_pages;$i++)
        {
            $this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> ";
        }
        $this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
    }
    $this->low = ($this->current_page <= 0) ? 0:($this->current_page-1) * $this->items_per_page;
    if($this->current_page <= 0) $this->items_per_page = 0;
    $this->limit = ($_GET['ipp'] == 'All') ? "":" LIMIT $this->low,$this->items_per_page";
}
function display_items_per_page()
{
    $items = '';
    if(!isset($_GET[ipp])) $this->items_per_page = $this->default_ipp;
    foreach($this->ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
    return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value+'$this->querystring';return false\">$items</select>\n";
}
function display_jump_menu()
{
    for($i=1;$i<=$this->num_pages;$i++)
    {
        $option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
    }
    return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page$this->querystring';return false\">$option</select>\n";
}
function display_pages()
{
    return $this->return;
}
  }
 ?>

我已经使用以下复选框执行了过滤器:

    <input type="checkbox" id="checkbox1" class="checkbox1" value="<?php echo $suburb['suburb_name']?>" name="Suburb_check[]" onClick="changeResults();" onChange="" ><?php echo $suburb['suburb_name']?>  <span class="grey">(<?php echo $suburb['total']?>)</span>

过滤器的Javascript / ajax代码

function changeResults(){
    var data = { 'venue[]' : []};
        $("input:checked").each(function() {
            var chck1 = $(this).val();
            //alert(chck1);
            data['venue[]'].push($(this).val());

    });
$.ajax({
     type : 'POST',
     url : 'process.php',
     data : data,
     success : function(data){
          $('#project_section').html(data); // replace the contents coming from php file
            }  
        });
    }

process.php文件

include_once("includes/classes/db_connect.php");
include_once("pagination/paginator.class.php");

$pages = new Paginator();

$value= array();

foreach($_POST as $key=>$value)
{
    $value[] = $venue[$key][$value];    
}
$countArray = count($value);

//echo $countArray;
/*echo "<pre>";
    print_r($value);
echo "</pre>";
exit;*/

if($countArray=='2')
{
        $where = "cities.city_name like '%".$_SESSION['$cityName']."%' and suburbs.suburb_name ='".$value[0]."' ";
}
else if($countArray=='3')
{
       $where = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name ='".$value[0]."' or suburbs.suburb_name ='".$value[1]."')";
}
else if($countArray=='4')
{
$where = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name ='".$value[0]."' or suburbs.suburb_name ='".$value[1]."' or suburbs.suburb_name ='".$value[2]."')";
}
else if($countArray=='5')
{
        $where = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name ='".$value[0]."' or suburbs.suburb_name ='".$value[1]."' or suburbs.suburb_name ='".$value[2]."' or suburbs.suburb_name ='".$value[3]."')";
}
else{
    $where = "cities.city_name like '%".$_SESSION['$cityName']."%' " ;
}

$countSql="SELECT count(*) as total from properties inner join cities on properties.city_id=cities.city_id inner join suburbs on properties.suburb_id=suburbs.suburb_id where ".$where." ";

//echo $countSql;
$resultCount = mysql_query($countSql);
$data = mysql_fetch_row($resultCount);
$pages->items_total = $data[0];
$pages->mid_range = 2;
$pages->paginate();
echo $pages->display_pages();       
echo $pages->display_items_per_page();

$sql="SELECT * from properties inner join cities on properties.city_id=cities.city_id inner join suburbs on properties.suburb_id=suburbs.suburb_id where ".$where." $pages->limit";

//echo $sql;
$result = mysql_query($sql);
//$data = mysql_fetch_assoc($result);
/*echo "<pre>" ;
print_r($data);
echo "</pre>" ; */
while($row=mysql_fetch_assoc($result))
{
      ?>
      <div class="projectlisttiger" id="propertyList">

                <div class="spacer5">&nbsp;</div>
                <div class="listnewimg flt">
                    <a href="p-kolte-patil-cilantro-wagholi-pune.php">
                        <img src="admin/uploads/<?php echo ($row['property_cover_image']) ?>" width="186" height="125" border="0">
                        <!--<img src="admin/uploads/Cilantra1/1cilantra-large.jpg" width="186" height="125" border="0">-->
                    </a>
                     <!--<div class="newlistlaunch"><a href="p-kolte-patil-cilantro-wagholi-pune.php"><img width="65" height="65" border="0" src="images/projects/kolte-patil/cilantra/new_launch_blue.png"></a>
                     </div>-->                              
                </div>

                <div class="listright">
                    <div style="width:498px; height:42px;" class="flt">
                        <div class="list-logo flt">
                            <div class="buildborder"><a href="p-kolte-patil-cilantro-wagholi-pune.php"><img width="80" height="36" border="0" align="absmiddle" alt="Kolte Patil" src="admin/uploads/<?php echo $row['builder_logo']?>"></a>
                            </div>
                               <div class="tablistname"><a href="p-kolte-patil-cilantro-wagholi-pune.php"><?php echo $row['property_name'] ?></a></div>
                        </div>   
                        <?php if ($row['property_price_min']!=0) { ?>      
                        <div class="listprice">
                            <img width="18" height="18" align="absmiddle" src="images/city/rupee_icon.gif"> <?php echo $row['property_price_min'] ?> Lacs - <?php echo $row['property_price_max'] ?> Lacs       
                        </div>
                        <?php } else { ?>
                        <div class="listprice">
                             <img width="18" height="18" align="absmiddle" src="images/city/rupee_icon.gif">Price on Request
                        </div>
                        <?php } ?>

                    </div>

                        <div class="spacer3">&nbsp;</div>

                    <div class="listbox">
                        <a href="p-kolte-patil-cilantro-wagholi-pune.php"><strong>Address</strong>:<?php echo $row['locality_name'] ?>, <?php echo $row['city_name'] ?><br> <strong>Types</strong>: 2BHK &amp; 3BHK
                        <br><strong>Sizes:</strong> <?php echo $row['property_size_min'] ?> sqft - <?php echo $row['property_size_max'] ?> sqft </a>
                    </div>

                    <div style="margin-left:-3px;" class="flt">
                        <div style="width:110px;" class="flt"><a style="text-decoration:none;" href="p-kolte-patil-cilantro-wagholi-pune.php"><input type="button" value="View Details" class="detail_project"></a>
                        </div>     
                      <div style="width:110px;" class="flt"><input type="button" onClick="showEnqForm('2659','Cilantro'); return false;" value="Enquire Now" class="enquire_project"></div>
                    </div>
                           <div class="spacer">&nbsp;</div>                                 
                </div>
                <div class="spacer15">&nbsp;</div>              
       </div>

我返回分页的结果,但是当我单击页码时,将我带到process.php,因为分页类使用 $ _SERVER [PHP_SELF]
如何在不更改页面url的情况下对结果进行分页,即使用ajax实施。我不能做太多更改,如果对此进行修改可以使它起作用,那将很有用。(这就是为什么我试图添加尽可能多的代码。)对不起,如果太多。
谢谢

编辑 @Gavin这是我的process.php

  <?php session_start();
  if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
    include('processRegion.php');
    die();
}
include_once("includes/classes/db_connect.php");
include_once("pagination/paginator.class.php");
$pages = new Paginator();
            if(isset($_GET['dataString']))
               {
                    $regionValue =  $_GET['dataString'];
                    //echo "region=".$regionValue;
               }
else{
        $regionValue = $_POST['dataString'];
}
$reqValue = "'".$regionValue."'";

echo $reqValue;

$arr = explode(",",$reqValue);
//print_r($arr);
$getBack = implode("','",$arr);

$beds = "'".$_POST['beds'];
//echo ($beds);
$arrBeds= explode(",",$beds);
//print_r($arrBeds);
$getBedValue = implode("','",$arrBeds);
$finalBedValue = substr($getBedValue,0,-2);

if(isset($_POST['beds']) && $_POST['beds']!=" ")
{
    $cityNameAndRegionName = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name in (".$getBack.")) and (properties_type.bed_type in (".$finalBedValue."))"; 
}
else
{
    $cityNameAndRegionName = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name in (".$getBack."))";
}

$countSql="SELECT count(*) as total from properties inner join cities on properties.city_id=cities.city_id inner join suburbs on properties.suburb_id=suburbs.suburb_id left outer join properties_type on properties.property_id=properties_type.property_id where ".$cityNameAndRegionName." ";
    ?>
    <?php include_once("processRegion.php"); ?>

*带有HTML的 *processRegion.php

<div class="flt width710" id="">
            <div style="float:right" id="toppagesel">
            <?php

            //Query processed here
        ?>
            </div>
                    </div>
        <div class="spacer15">&nbsp;</div>
                <div><strong>Results for properties for sale</strong> in <?php echo ucfirst($_SESSION['$cityName']) ?>.</div>
        <div class="spacer15">&nbsp;</div>

         <div class="width710" id="displayProp">
        <?php while($row=mysql_fetch_assoc($result))
    { ?>  
            <div class="projectlisttiger" id="propertyList">

                <div class="spacer5">&nbsp;</div>
                  <div class="listnewimg flt">
                    <a href="p-kolte-patil-cilantro-wagholi-pune.php">
                        <img src="admin/uploads/<?php echo ($row['property_cover_image']) ?>" width="186" height="125" border="0">

                </div>

                <div class="listright">
                    <div style="width:498px; height:42px;" class="flt">
                        <div class="list-logo flt">
                            <div class="buildborder"><a href="p-kolte-patil-cilantro-wagholi-pune.php"><img width="80" height="36" border="0" align="absmiddle" alt="Kolte Patil" src="admin/uploads/<?php echo $row['builder_logo']?>"></a>
                            </div>
                               <div class="tablistname"><a href="p-kolte-patil-cilantro-wagholi-pune.php"><?php echo $row['property_name'] ?></a></div>
                        </div>   
                        <?php if ($row['property_price_min']!=0) { ?>      
                        <div class="listprice">
                            <img width="18" height="18" align="absmiddle" src="images/city/rupee_icon.gif"> <?php echo $row['property_price_min'] ?> Lacs - <?php echo $row['property_price_max'] ?> Lacs       
                        </div>
                        <?php } else { ?>
                        <div class="listprice">
                             <img width="18" height="18" align="absmiddle" src="images/city/rupee_icon.gif">Price on Request
                        </div>
                        <?php } ?>

                    </div>
                    <div class="spacer3">&nbsp;</div>

                    <div class="listbox">
                        <a href="p-kolte-patil-cilantro-wagholi-pune.php"><strong>Address</strong>:<?php echo $row['locality_name'] ?>, <?php echo $row['city_name'] ?><br> <strong>Types</strong>: 2BHK &amp; 3BHK
                        <br><strong>Sizes:</strong> <?php echo $row['property_size_min'] ?> sqft - <?php echo $row['property_size_max'] ?> sqft </a>
                    </div>

                    <div style="margin-left:-3px;" class="flt">
                        <div style="width:110px;" class="flt"><a style="text-decoration:none;" href="p-kolte-patil-cilantro-wagholi-pune.php"><input type="button" value="View Details" class="detail_project"></a>
                        </div>     
                      <div style="width:110px;" class="flt"><input type="button" onClick="showEnqForm('2659','Cilantro'); return false;" value="Enquire Now" class="enquire_project"></div>
                    </div>
                           <div class="spacer">&nbsp;</div>                                 
                </div>
                <div class="spacer15">&nbsp;</div>              
       </div>
       <?php
            }
       ?>
  <div class="spacer15">&nbsp;</div>
</div>

<div style="float:right" id="toppagesel">
            <?php 
                echo $pages->display_pages();
                echo $pages->display_items_per_page();
            ?>
</div>

问题答案:

如我的评论所述。

您可以执行以下操作:

$(document).ready(function()
{
    $('.paginate').live('click', function(e)
    {
        e.preventDefault();
        var btnPage = $(this);
        $.ajax(
        {
            url : btnPage.attr('href'),
            success : function(resp)
            {
                // replace current results with new results.
                $('#project_section').html(resp);
            },
            error : function()
            {
                window.location.href = btnPage.attr('href');
            }
        });
    });
});

上面的代码将复制您单击每个分页链接的位置。

我接下来建议做的是将生成“结果”列表的PHP代码和HTML分离到一个单独的文件中。

这样,在显示结果的页面上,您可以简单地使用include('path-to-results- file.php');适用于非ajax请求的内容,然后可以执行以下操作:

Process.php

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
    include('path-to-results-file.php');
    die();
}

上面的代码将检测是否已发出ajax请求,如果已发出,则不显示整个页面(包括结果),而仅显示结果和分页。

更新以包含更好的解释

下面是我的意思的一个非常简单的例子。

当前process.php

    <?
    // currently contains all of the code required
    // to query the database etc.
?>
<html>
<head>...</head>
<body>
    <!-- header content -->
    <table>
    <?
        // currently contains all of the code required to display
        // the results table and pagination links.
    ?>
    </table>
    <!-- footer content -->
</body>
</html>

新的process.php

<?
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
    {
        include('path-to-results-file.php');
        die();
    }
?>
<html>
<head>...</head>
<body>
    <!-- header content -->
    <? include('path-to-results-file.php'); ?>
    <!-- footer content -->
</body>
</html>

新的path-to-results-file.php

<?
    // currently contains all of the code required
    // to query the database etc.
?>
<table>
<?
    // currently contains all of the code required to display
    // the results table and pagination links.
?>
</table>

现在…当您process.php通过浏览器正常访问或禁用javascript时。它将像现在没有Javascript一样简单地工作。

当您转到process.php然后单击其中一个分页链接(已启用javascript)时,process.php将检测到您正在使用Ajax,并且仅发送回结果表。



 类似资料:
  • 问题内容: 我将GWT用于UI,将Hibernate / Spring用于业务层。以下GWT小部件用于显示记录。(http://collectionofdemos.appspot.com/demo/com.google.gwt.gen2.demo.scrolltable.PagingScrollTableDemo /PagingScrollTableDemo.html )。我认为排序是在客户端完成

  • 0927,美团二面,1h 1. 自我介绍 2. 深挖项目 1. SwiftUI 怎么样,和 UIKit 比如何,你是怎么学的 Swift,有没有做方案的选型 2. 动画如何实现(自己瞎掰头,他说差不多是这个意思) 3. 序列化怎么做的 4. 网络库用的什么 5. iOS 这边 MVVM,APNs 怎么做的 3. 有没有了解过一些其他的移动端框架,Flutter 画点粒度做 UI 4. 实验室项目

  • 客户端分享 对接前提 1.需要APP本身有客户端分享功能和对应的分享接口 2.在管理后台配置好并开启分享功能 分享定制 如果开发者已有自己的一套H5分享接口,可以联系兑吧技术支持,由技术支持根据分享接口要求做定制。请联系兑吧技术支持协助配置。 分享案例 1.客户端分享兑吧活动 2.分享结果 3.点击分享跳转兑吧活动页 4.点击参与跳转下载页

  • 我需要从可分页REST API的所有页面获取项目。我还需要开始处理项目,只要它们可用,不需要等待所有页面加载。为了做到这一点,我使用了Spring WebFlux及其WebClient,并希望返回Flux 当前窗口的大小 当前窗口中的剩余时间 在窗口中请求配额 请求留在当前窗口中 对单个页面请求的响应如下所示: 数据数组包含实际项目,而元对象包含分页信息。 我当前的解决方案首先执行一个“虚拟”请求

  • 贝壳云笔记客户端是一个基于 electron-vue 开发的云储存平台。 运行 git clone https://github.com/Beatrice950201/eibk_client.gitcd eibk_clientnpm install# 运行开发模式npm run dev# 打包安装文件 npm run build# 请自行配置src/renderer/tool/config.js

  • 我想在一些计算机之间建立点对点连接,这样用户就可以在没有外部服务器的情况下聊天和交换文件。我最初的想法如下: 我在服务器上制作了一个中央服务器插座,所有应用程序都可以连接到该插座。此ServerSocket跟踪已连接的套接字(客户端),并将新连接的客户端的IP和端口提供给所有其他客户端。每个客户端都会创建一个新的ServerSocket,所有客户端都可以连接到它。 换句话说:每个客户端都有一个Se