html+php 调用数据库文章并且显示出来滚动到底部自动加载没有更多内容的时候弹出提示
以下是一个使用HTML和PHP调用数据库文章并显示出来的例子,滚动到底部时会自动加载更多内容,当没有更多内容时会弹出提示。
首先,创建一个包含数据库连接信息的config.php文件:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
?>
然后,创建一个index.php文件,用于显示文章列表:
<!DOCTYPE html>
<html>
<head>
<title>文章列表</title>
<style>
#article-list {
margin-top: 20px;
font-size: 18px;
}
.loading {
text-align: center;
margin-top: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
var loading = false;
var page = 1;
$(document).ready(function() {
loadArticles();
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
loadArticles();
}
});
});
function loadArticles() {
if(loading) return;
loading = true;
$('.loading').show();
$.ajax({
url: 'get_articles.php',
method: 'POST',
data: {page: page},
dataType: 'html',
success: function(response) {
$('.loading').hide();
if(response.trim() != '') {
$('#article-list').append(response);
page++;
} else {
alert('没有更多内容了!');
}
loading = false;
}
});
}
</script>
</head>
<body>
<div id="article-list">
<!-- 文章列表将显示在这里 -->
</div>
<div class="loading" style="display: none;">
加载中...
</div>
</body>
</html>
接下来,创建一个get_articles.php文件,用于从数据库中获取文章并返回HTML格式的文章列表:
<?php
include 'config.php';
$page = $_POST['page'];
$limit = 10; // 每页显示的文章数量
$offset = ($page - 1) * $limit;
$sql = "SELECT * FROM articles ORDER BY id DESC LIMIT $limit OFFSET $offset";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo '<div class="article">';
echo '<h2>' . $row['title'] . '</h2>';
echo '<p>' . $row['content'] . '</p>';
echo '</div>';
}
} else {
echo '';
}
$conn->close();
?>
最后,创建一个articles表(如果尚未创建)并插入一些测试数据:
CREATE TABLE articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL
);
INSERT INTO articles (title, content) VALUES ('文章标题1', '文章内容1');
INSERT INTO articles (title, content) VALUES ('文章标题2', '文章内容2');
INSERT INTO articles (title, content) VALUES ('文章标题3', '文章内容3');
...
现在,当访问index.php时,文章列表将显示在页面上。当滚动到页面底部时,将自动加载更多文章,直到没有更多内容时将弹出提示
原文地址: http://www.cveoy.top/t/topic/h8es 著作权归作者所有。请勿转载和采集!