我正在做的是使用jQuery,AJAX和PHP进行无限滚动,但是当你必须加载数据时,我会在页面顶部重新加载页面,而不是在它几乎位于底部时在页面中,我留下了我的jQuery和AJAX代码。提前谢谢!
<script type="text/javascript">
var start = 0;
var limit = 5;
var reachedMax = false;
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height())
getData();
});
$(document).ready(function () {
getData();
});
function getData() {
if (reachedMax)
return;
$.ajax({
url: 'publicaciones.php',
method: 'POST',
dataType: 'text',
data: {
getData: 1,
start: start,
limit: limit
},
success: function(response) {
if (response == "reachedMax")
reachedMax = true;
else {
start += limit;
$(".results").append(response);
}
}
});
}
</script>
这是我的PHP,我添加代码来解决我的问题。我认为我的PHP是必要的。
<?php
session_start();
include ('../conexion.php');
if(isset($_SESSION['id']))
{
$id = mysqli_real_escape_string($conexion, $_SESSION['id']);
$infouser = mysqli_query($conexion, "SELECT * FROM users WHERE id = $id");
$use = mysqli_fetch_array($infouser);
}
if(isset($_POST['getData']))
{
$start = mysqli_real_escape_string($conexion,$_POST['start']);
$limit = mysqli_real_escape_string($conexion,$_POST['limit']);
$consulta = mysqli_query($conexion, "SELECT * FROM publicaciones ORDER BY id_pub DESC LIMIT $start, $limit");
if(mysqli_num_rows($consulta) > 0)
{
$response = "";
while($data = mysqli_fetch_array($consulta)) {
$response .= "
<div class='card mt-3 border-0 rounded-0'>
<div class='card-body'>
<div class='row'>
<div class='col-sm-2'>
<div class='img-user rounded-circle'>
<img class='img-fluid-pub' src='../avatars/".$use['avatar']."' alt='User Image'>
</div>
</div>
<div class='col-sm-10'>
<a class='text-muted h3' href='perfil.php?id=".$use['id']."'>".$use['usuario']."</a><h3>Seguir</h3>
<p>".$data['fecha']."</p>
<p>".$data['titulo']." Me gusta</p>
<p id='descripcion'>".$data['descripcion']."</p>
<p class='leermas' onclick='leerMas(this);'>Leer más...</p>
<video controls>
<source src='../anadir-publicacion/publicaciones/".$data['video']."' type='video/mp4'>
Your browser does not support HTML5 video.
</video>
<p>Kcal: ".$data['kcal']." CarbHid: ".$data['carbohidratos']." Prot: ".$data['proteinas']." Gras: ".$data['grasas']." Tiempo: ".$data['tiempo']."m Personas: ".$data['personas']." Dinero aprox: ".$data['precio']."€ Categoría: ".$data['categoria']."</p>
</div>
</div>
</div>
</div>
";
}
exit($response);
}
else
exit('reachedMax');
}
?>
答案 0 :(得分:1)
很正常
$(window).scrollTop()
开头等于0
并且$(document).height()
等于$(window).height()
所以是0 == 0在页面顶部
你想要什么
var nb_px_before_load = 100
if($(window).innerHeight() - $(window).scrollTop() < nb_px_before_load){
getData();
}
您可以使用带有断点的chrome devTools轻松查看