使用 php 和 ajax 从文件中分页

2024-01-27

我想在 php 中使用 ajax 进行分页,并且数据来自文件。在搜索关键字时,页面显示文件中的前 20 条记录,但现在我想要文件中的下一条剩余记录,它应该使用分页。请问有什么建议吗?

$keyword=$_POST['data'];
$file = file_get_contents("http://localhost:8080/searchengine/searchDeals?searchKeyword=".$keyword."");
$output = "[";
$line = 1;
if ( !($fp = fopen($file, "r") ) )
exit("Unable to open the input file.");
while( !feof($fp) && $line <= 20 ) 
{
if($line != 20){
 $output = $output.fgets($fp).","; 
  }else{    
 $output = $output.fgets($fp); 
}
 $line++;
}
fclose($fp);
$output = $output."]";
echo $output;

首先,您需要计算总页数。它是floor(number_of_lines_in_file / 20).

要切换到不同的页面,您必须传递选定的页面变量(例如通过 $_GET)并从中获取行$page_number - 1 * 20 to $page_number * 20。您可以从循环中获取线条,也可以考虑更高级的东西,例如使用fseek或许...

But最简单的方法可能是使用 PHPfile()函数,它将文件保存到一个数组中,您只需使用以下命令获取所需的行部分array_slice.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 php 和 ajax 从文件中分页 的相关文章

随机推荐