我正在发送一个公式,该公式通过PHP从MySQL数据库中检索数据。我想通过滚动逐步地收集数据,这是一种用Javascript编写的“无限滚动”实现。一切正常,除了每次我从HTML文档中的脚本内部调用PHP函数时,都找不到增加指定从检索数据开始的行的变量的值的事实。
下面是index.php代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script-->
<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/copy_code.js"></script>
<script src="js/scroll.js"></script>
<script src="js/preloader.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
<?php
include("dbconnect.php");
include("search.php");
?>
</head>
<body>
<!-- Preloader -->
<div class="preloader"></div>
<!-- scroll to top buttom -->
<a href="#" id="scroll"><span></span></a>
<article>
<div class="entry_content">
<FORM method=post action='<?php echo htmlentities($_SERVER['PHP_SELF']); ?>'>
<!-- My FORM -->
</FORM>
<div id="load_data"> </div>
<div id="load_data_message"></div>
</div>
</article>
</body>
</html>
<script>
$(document).ready(function(){
var limit = 10;
var start = 0;
var action = 'inactive';
console.log("Limite + Start:")
console.log(limit);
console.log(start);
function load_data(limit, start)
{
console.log("Limite & Start");
console.log(limit);
console.log(start);
var data="<?php echo search(limit, start); ?>";
$('#load_data').append(data);
if(data == '') /* No data: active, "no data found" */
{
$('#load_data_message').html("<button type='button' class='btn btn-info'>No Data Found</button>");
action = 'active';
}
else /* data: active, "Please wait..." */
{
$('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
action = "inactive";
}
}
if(action == 'inactive')
{
console.log("Inactiva");
action = 'active';
load_data(limit, start);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
{
action = 'active';
console.log("Activaaaaaa. Start: ");
start = start + limit;
console.log(start);
setTimeout(function(){
load_data(limit, start);
}, 1000);
}
});
});
</script>
search(limit,start)函数位于search.php文件中,它以这种方式检索值:
$result = $mysqli->query("SELECT * FROM MyTable WHERE $conditions LIMIT $start, $limit");
while ($row = mysqli_fetch_object($result)) {
echo [...]
}
每次从index.php调用load_data(limit,start)函数时,我都要增加此$ start变量。
我曾尝试创建cookie(由于无法在刷新前获取新的cookie值而无法使用),在搜索功能内创建静态php变量并增加其值(无法工作,我不知道为什么),通过表单传递变量并增加其值,...但无济于事。
我提到过,您可以在javascript中实现变量的增量,因此可以组合成一个基于ajax的简单无限滚动系统。为了简单起见,没有数据库查询,但是这里有主要逻辑
为了在页面加载后调用任何PHP函数,您需要使用XMLHttpRequest
(又名Ajax)或更新的fetch
API向某个脚本(或同一页面)发送HTTP请求,并使用回调函数以某种方式附加响应。
在上面,没有使用ajax,因此初始页面加载了由PHP(var data="<?php echo search(limit, start); ?>";
)编写的静态Javascript变量-一旦该结果集被javascript函数使用,就无法获取现有的下一组记录。使用标准格式submit
无效,因此在上面的代码中我看不到要点。
由于您要做的就是使用$start
变量来更改查询返回的结果,因此不需要任何会话或cookie存储-只需让javascript递增相关计数器即可。
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
$page=!empty( $_POST['page'] ) ? $_POST['page'] : 10;
$limit=!empty( $_POST['limit'] ) ? $_POST['limit'] : 10;
/*
call / query database to fetch the next portion of results.
Here it is simply emulating the return of data
*/
for( $i=0; $i < $limit; $i++ ){
$sql=sprintf('select * from `table` order by id limit %d,%d', $page, $limit);
printf( '<div>Record #%d from %s</div>', $i+1, $sql );
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Infinite scroller</title>
<script>
const setruntime=function( callback ){
return document.addEventListener('DOMContentLoaded', callback );
}
const ajax=function(url,params,callback){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback.call( this, this.response )
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.send( params );
};
const initialise=function(){
var page=limit=10;
var status=true;
const scrollhandler=function(e){
if( ( window.innerHeight + window.scrollY ) >= document.body.offsetHeight ){
const url=location.href;
const payload={
'action':'scroll',
'page':page,
'limit':limit
};
const callback=function(r){
/* process and add response data somehow... */
let form = document.forms.geronimo;
form.insertAdjacentHTML( 'beforeend', r )
/* increment the page variable for the NEXT request */
page += limit;
/* once again set status to true to permit new ajax request */
status=true;
};
/* prepare the querystring for the request */
let params=Object.keys( payload ).map( k=>{
return [k,payload[k]].join('=')
}).join('&');
/* send the request */
if( status ) ajax( url, params, callback );
status=false;
}
}
document.addEventListener( 'scroll', scrollhandler );
};
setruntime( initialise );
</script>
<style>
body,body *{font-family:fantasy}
div{width:50%;float:none;margin:5rem auto;padding:3rem;border:1px dashed rgba(1,1,1,0.1);background-color:rgba(255,253,225,1)}
div:nth-child(even){background-color:rgba(255,243,243,1)}
</style>
</head>
<body>
<form name='geronimo' method='post'>
<?php
/* display the first X records, SCROLL to fetch subsequent X + PAGE records... */
for( $i=1; $i < 10; $i++ )printf( '<div>%d</div>', $i );
?>
</form>
</body>
</html>