search
HomeBackend DevelopmentPHP Tutorial【原创】分页高级教程:结合JQUERY做AJAX分页

本文主要结合JQUERY做无刷新分页。代码基本上和前两篇文章差不多,稍稍有所变动。本文中的翻页链接用JS编写。先上代码:
page4.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" /><title>结合jquery做ajax分页</title><style>body{ font-size:12px; font-family:Verdana, Arial, Helvetica, sans-serif}.page A{ padding:3px 5px; float:left; border:solid #CCCCCC 1px; text-decoration:none; font-size:12px; margin-left:1px; font-family:Verdana;color:#000000;}.page A.currentpage{ color:#FF0000; border: solid red 1px;}.page A:hover{ background-color:#CCCCCC;}</style><script language="javascript" src="jquery-1.7.1.min.js"></script></head><body><? //PHP分页实例//分页尺寸$page_size=10;$conn=mysql_connect("localhost","root","root") or die(mysql_error());mysql_select_db("xinyang");//计算总行数$total_records=mysql_num_rows(mysql_query("SELECT id from product"));//总页数$total_page=ceil($total_records/$page_size); $query=mysql_query("select * from product limit 0,$page_size")  or die(mysql_error());?><div class="recordlist"><ul><?while ($rs=mysql_fetch_array($query)){?>	 <li><?=$rs["id"]?>-<?=$rs["ename"]?></li><?}?></ul></div><div class='page'></div></body></html><script language="javascript">var total_page=<?=$total_page?>;var url="page5.php?page";//当前链接,格式如下,例如:?aa=1&page  ,somepage.php?action=1&cat=1&page$().ready(function(){	$(".page").html(pagination(1))		page_link();})function page_link(){	$(".page A").click(function(){		var page=parseInt($(this).attr("page")) 		$(".recordlist").load($(this).attr("href"),"",function(){$(".page").html(pagination(page));page_link();})		return false;	})}function pagination(current_page){ 	//翻页链接开始	current_page = current_page<=0 ? 1 : current_page;	current_page = current_page>total_page?total_page:current_page;	var page_link="";	if (total_page>1)	{		page_link="<a>一共"+total_page+"页</a>";		page_link+="<a>当前第"+current_page+"页</a>";		page_link+="<a href="+url+"=1 page=1>首页</a>";		if (current_page>1){			//页码大于1的时候,显示上一页翻页链接			var pre_page=current_page-1;			page_link+="<a  href='"+url+"="+pre_page+"' page="+pre_page+"><<</a>";		}		//翻页列表		//步进分页,翻页列表的数字始终只显示9个或者自定义的个数,本例定义只显示9个,当前页左右各显示4个页码		if (total_page>9)		{			if (current_page>4)			{				var from=current_page-4;				var to=current_page+4;				if (to>total_page)				{					var from=total_page-8;					var to=total_page;				}				 			}			else			{				var from=1;				var to=9;			}		}		else		{			var from=1;			var to=total_page;		}		for (var i=from;i<=to;i++)		{			if (i==current_page)			{				//高亮当前页页码				page_link+="<a href='"+url+"="+i+"' class='currentpage' page="+i+">"+i+"</a>";			}			else			{				page_link+="<a href='"+url+"="+i+"' page="+i+"  page="+i+">"+i+"</a>";			}		}		//页码小于总页数的时候显示下一页翻页链接		var next_page=current_page+1;		if(next_page<total_page)		{			page_link+="<a  href='"+url+"="+next_page+"' page="+next_page+">>></a>";		}		page_link+="<a  href='"+url+"="+total_page+"' page="+total_page+">最后一页</a>";	}	return page_link;}</script>


page5.php

<? $page=$_GET["page"]+0;$page= $page<=0 ? 1 : $page; //分页尺寸$page_size=10;$conn=mysql_connect("localhost","root","root") or die(mysql_error());mysql_select_db("xinyang");$offset=($page-1)*$page_size;$query=mysql_query("select * from product limit $offset,$page_size")  or die(mysql_error());?> <ul><?while ($rs=mysql_fetch_array($query)){?>	 <li><?=$rs["id"]?>-<?=$rs["ename"]?></li><?}?></ul>


回复讨论(解决方案)

本文的核心部分就是JS部分的 page_link()函数,当用户点击翻页链接之后,脚本将对div.recordlist绑定一个load事件,这个主要用来加载下一页的内容。
看看jquery手册上对load事件的说明:载入远程 HTML 文件代码并插入至 DOM 中。

如果我们仅仅只这样:
$(".recordlist").load($(this).attr("href")) 这样是可以翻页,但是问题出现了,发现翻页链接不能发生变化,,,所以需要在回调函数里面,重新初始化翻页链接,因此在回调函数总加入$(".page").html(pagination(page));这里初始化翻页之后,需要对.page A重新绑定click事件,因此在回调函数里面加上page_link().

由于是点击的的对象是.page A,点击之后,会发生跳转,因此必须终止跳转,所以必须加上return false来终止。。。



暂且说这么多,欢迎拍砖~

你将分页链接和内容做成一个模板  每次请求的时候把整个模板load这个模板就行

减少一些js操作

学习了…………

几点意见.
1 pagination 函数用意是拼接输出字符串,建议封装为模板.
2 此分页,没有考虑带上查询条件。

page5.php有什么 用吗?

好用,非常感谢

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor