使用jQuery AJAX PHP在页面滚动中加载PostgreSQL数据

194 阅读1分钟

无限滚动在页面上显示有限的记录,当页面滚动到页面底部时,会自动加载新的记录。

在本教程中,我展示了如何使用jQuery、AJAX和PHP在页面滚动中加载Postgresql数据。

1.表 的结构

我在这个例子中使用了posts

CREATE TABLE posts (
     id serial PRIMARY KEY,
     title varchar(100) NOT NULL,
     description text NOT NULL,
     link varchar(255) NOT NULL
)

2.配 置

为数据库配置创建config.php 文件。

完成代码

<?php

$host = "localhost";
$user = "postgres";
$password = "root";
$dbname = "tutorial";
$con = pg_connect("host=$host dbname=$dbname user=$user password=$password");

if (!$con) {
   die('Connection failed.');
}

3.H TML & PHP

我把3设置为$rowperpage (根据你想在页面上一次显示多少条记录来改变它的值)。

posts 表中获取记录总数,并将其分配给$allcount 变量。

在限制中使用$rowperpage 来获取记录。在获取的记录上进行循环并创建布局。

创建3个隐藏字段

  1. 存储起始位置。把它设置为0。
  2. 存储一次获取的行数。设置为3。
  3. 存储记录的总数。

完成的代码

<div class="container">

<?php

 include "config.php";

 // Row per page
 $rowperpage = 3;
 
 // counting total number of posts
 $sql = "select count(*) as allcount from posts";
 $result = pg_query($con,$sql);
 $records = pg_fetch_assoc($result);
 $allcount = $records['allcount'];

 // select first 3 posts
 $sql = "select * from posts order by id asc limit $rowperpage OFFSET 0";

 $records = pg_query($con, $sql);

 while ($row = pg_fetch_assoc($records)) {

    $id = $row['id'];
    $title = $row['title'];
    $content = $row['description'];
    $shortcontent = substr($content, 0, 160)."...";
    $link = $row['link'];
?>

    <div class="post" id="post_<?php echo $id; ?>">
       <h2><?php echo $title; ?></h2>
       <p>
          <?php echo $shortcontent; ?>
       </p>
       <a href="<?= $link ?>" target="_blank" class="more">More</a>
    </div>

<?php
}
?>

  <input type="hidden" id="start" value="0">
  <input type="hidden" id="rowperpage" value="<?= $rowperpage ?>">
  <input type="hidden" id="totalrecords" value="<?= $allcount ?>">

</div>

4.A JAX

创建ajaxfile.php 文件。

$start 的默认值设为0,将$rowperpage 的默认值设为3。如果值是POST,则将值分配给变量。

posts 表中获取记录,在 LIMIT 中使用 POST$rowperpage$start 。在获取的记录上循环,创建HTML布局,并将其分配给$html 变量。

返回$html

完成的代码

<?php
## Database configuration
include 'config.php';

$start = 0;$rowperpage = 3;
if(isset($_POST['start'])){
   $start = $_POST['start']; 
}
if(isset($_POST['rowperpage'])){
   $rowperpage = $_POST['rowperpage']; 
}

## Fetch records
$sql = 'select * from posts order by id desc limit '.$rowperpage.' OFFSET '.$start;

$records = pg_query($con, $sql);
$html = '';

while ($row = pg_fetch_assoc($records)) {
   $id = $row['id'];
   $title = $row['title'];
   $content = $row['description'];
   $shortcontent = substr($content, 0, 160)."...";
   $link = $row['link'];

   // Creating HTML structure
   $html .= '<div id="post_'.$id.'" class="post">';
   $html .= '<h2>'.$title.'</h2>';
   $html .= '<p>'.$shortcontent.'</p>';
   $html .= "<a href='".$link."' target='_blank' class='more'>More</a>";
   $html .= '</div>';

}

echo $html;

5. jQuery

创建2个函数 -

  • checkWindowSize() -使用这个函数来检查高度,通过调用fetchData() 函数加载新内容。同时,如果页面没有足够的内容,在页面第一次加载时调用这个函数来显示新的内容。
  • fetchData() -使用这个函数来获取记录。

从隐藏元素中读取数值,并将其分配给变量。将rowperpagestart ,并检查它是否是<= allcount ,如果是则发送AJAX POST请求到ajaxfile.php ,将startrowperpage 作为数据。

在成功的回调中,在最后一个class="post" 元素后添加响应,并再次通过调用checkWindowSize() 检查窗口大小。

定义2个事件 -

  • scroll -检测页面滚动并检查滚动是否到达底部。如果达到,则调用fetchData() ,以获取新的记录。
  • touchmove -这是为移动设备检测滚动。

完成的代码

checkWindowSize();

// Check if the page has enough content or not. If not then fetch records
function checkWindowSize(){
   if($(window).height() >= $(document).height()){
      // Fetch records
      fetchData();
   }
}

// Fetch records
function fetchData(){
   var start = Number($('#start').val());
   var allcount = Number($('#totalrecords').val());
   var rowperpage = Number($('#rowperpage').val());
   start = start + rowperpage;

   if(start <= allcount){
      $('#start').val(start);

      $.ajax({
         url:"ajaxfile.php",
         type: 'post',
         data: {start:start,rowperpage: rowperpage},
         success: function(response){

            // Add
            $(".post:last").after(response).show().fadeIn("slow");

            // Check if the page has enough content or not. If not then fetch records
            checkWindowSize();
         }
      });
   }
}

$(document).on('touchmove', onScroll); // for mobile

function onScroll(){

   if($(window).scrollTop() > $(document).height() - $(window).height()-100) {
      fetchData(); 
   }
}

$(window).scroll(function(){

   var position = $(window).scrollTop();
   var bottom = $(document).height() - $(window).height();

   if( position == bottom ){
      fetchData(); 
   }

});

6.C SS

.container{
  width: 55%;
  margin: 0 auto;
  border: 0px solid black;
  padding: 10px 0px;
}

/* post */.post{
  width: 97%;
  min-height: 200px;
  padding: 5px;
  border: 1px solid gray;
  margin-bottom: 15px;
}

.post h2{
  letter-spacing: 1px;
  font-weight: normal;
  font-family: sans-serif;
}


.post p{
  letter-spacing: 1px;
  text-overflow: ellipsis;
  line-height: 25px;
}

/* more link */.more{
  color: blue;
  text-decoration: none;
  letter-spacing: 1px;
  font-size: 16px;
}

7.输 出


8.总 结

根据你的要求,调整$rowperpage 值。即使页面在第一次加载时内容较少,这段代码也能发挥作用。

你可以在这里查看本教程的MySQL版本。

如果你觉得本教程有帮助,那么别忘了分享。