利用ajax实现web项目的无刷新分页(最新版)

在学习中用ajax实现web项目的无刷新分页,代码中注释较少,有没看懂的可以留言

jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
	a{
		text-decoration:none;
	}
	li{
		list-style-type:none;
		margin-top:10px;
	}
	#d2{
		width:100%;
		text-align: center;
	}
	#p1{
		margin-left:150px;
	}
	#p2{
		/* margin-left:100px; */
	
	}
	#p3{
		width:100%;
		display: inline;
	}
</style>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
var model = {  
        pageSize: 3,      //每页列表的行数  
        currPageNo:1,
        pageCount: 1//总页数
    }; 
var tid="";
var n=1;
    
	$(function(){
		show_topics();
		show_news();
		$("#a1").click(firstPage);
		$("#a2").click(prePage);
		$("#a3").click(nextPage);
		$("#a4").click(lastPage);
		$('body').on('click','#p1 a',function(){
			tid=this.getAttribute("id"); 
			$("#p3").empty();                             
	 		show_news();
		});	
		
		$('body').on('click','#p3 input',function(){
			model.currPageNo=this.getAttribute("value");                            
	 		$.getJSON("newsServlet.to","pageIndex=" + model.currPageNo+"&tid="+tid,function(data){
	 			var newsdata = eval(data);              
                    model.pageSize = newsdata.pageSize;
                    model.pageCount = newsdata.totalPageCount;
                    model.currPageNo=newsdata.currPageNo;                    
                $("#u1").empty();   //清空div中内容                        
                $.each(newsdata.newsList, function (index, content) {
                  $("#u1").append("<li><a href='javascript:'>"+content.ntitle+"</a>&nbsp;&nbsp;&nbsp;&nbsp;"+content.ncreatedate+"</li>");


                });
                $("#s1").html("["+model.currPageNo+"/"+ model.pageCount+"]");                                       
	 		});
		});	
	});
	
	function show_topics(){
		$.getJSON("topicServlet.to",function(data){
				console.log(data);
			$(data).each(function(i,topic){
				$("#p1").append("<a href='javascript:' id="+topic.tid+">"+topic.tname+"</a>&nbsp;&nbsp;&nbsp;&nbsp;");
			});
		});
	}
	
	function show_news() {  
        $.ajax({  
            type:"POST",  
            dataType:"json",  
            url:"newsServlet.to",  
            data:"pageIndex=" + model.currPageNo+"&tid="+tid,
            //async:false, 
            //cache:false, 
            success: function(data) {
                var newsdata = eval(data);              
                    model.pageSize = newsdata.pageSize;
                    model.pageCount = newsdata.totalPageCount;
                    model.currPageNo=newsdata.currPageNo;                    
                $("#u1").empty();   //清空div中内容        
                
                $.each(newsdata.newsList, function (index, content) {
                  $("#u1").append("<li><a href='javascript:'>"+content.ntitle+"</a>&nbsp;&nbsp;&nbsp;&nbsp;"+content.ncreatedate+"</li>");


                });
               	for(var i=1;i<=model.pageCount;i++){
               		$("#p3").append("<input style='margin-left: 5px' type='button' value="+i+">");
               	}
                $("#s1").html("["+model.currPageNo+"/"+ model.pageCount+"]");                           
            },
            error:function(){
                $("#u1").empty();   //清空div中内容
                $("#u1").append('<strong><p style="text-indent:2em">No Contents</p></strong>');
            }
        });  
        
    }
    
function firstPage(){
	 model.currPageNo=1;
	  $.ajax({  
          type:"POST",  
          dataType:"json",  
          url:"newsServlet.to",   //回发到的页面  
          data:"pageIndex=" + model.currPageNo+"&tid="+tid,
          success: common
        });
}
 	
function prePage(){
 		if(model.currPageNo==1){
 			model.currPageNo=1;
 		}else{
 			model.currPageNo=model.currPageNo-1;
 		}		 
 		  $.ajax({  
            type:"POST",  
            dataType:"json",  
            url:"newsServlet.to",   //回发到的页面  
            data:"pageIndex=" + model.currPageNo+"&tid="+tid,
            success: common
          });
 	}
 	
 	function nextPage(){
 		if(model.currPageNo==model.pageCount){
 			model.currPageNo=model.pageCount;
 		}else{
 			model.currPageNo=model.currPageNo+1;
 		}		 
 		  $.ajax({  
            type:"POST",  
            dataType:"json",  
            url:"newsServlet.to",   //回发到的页面  
            data:"pageIndex=" + model.currPageNo+"&tid="+tid,
            success: common
          });
 	}
 	
 	function lastPage(){
 		  model.currPageNo=model.pageCount;		 
 		  $.ajax({  
            type:"POST",  
            dataType:"json",  
            url:"newsServlet.to",   //回发到的页面  
            data:"pageIndex=" + model.currPageNo+"&tid="+tid,
            success: common
          });
 	}
 	
 	function common(data){
 		 var newsdata = eval(data);  
     	 $("#u1").empty();   //清空div中内容                        
         $.each(newsdata.newsList, function (index, content) {
	         $("#u1").append("<li><a href='javascript:'>"+content.ntitle+"</a>&nbsp;&nbsp;&nbsp;&nbsp;"+content.ncreatedate+"</li>");
	     });
         $("#s1").html("["+model.currPageNo+"/"+ model.pageCount+"]"); 
 	}
</script>
</head>
<body>
	<div id="d1">
		<p id="p1"></p>
	</div>
	<hr>
	<div id="d2">
		<ul id="u1"></ul>
		<p id="p2">当前页数:<span id="s1"></span>&nbsp;&nbsp;&nbsp;&nbsp;
		<a id="a1" href='javascript:'>首页</a>
		<a id="a2" href='javascript:'>上一页</a>
		<span id="p3"></span>
		<a id="a3" href='javascript:'>下一页</a>
		<a id="a4" href='javascript:'>末页</a>
		</p>
	</div>
</body>
</html>

后端servlet

package servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSON;


import dao.NewsDao;
import dao.TopicDao;
import dao.impl.NewsDaoImpl;
import dao.impl.TopicDaoImpl;


import entity.News;
import entity.Page;
import entity.Topic;


@WebServlet("*.to")
public class TestServlet extends HttpServlet {


	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		res.setContentType("text/html;charset=utf-8");
		String p=req.getServletPath();
		PrintWriter out=res.getWriter();
		if("/newsServlet.to".equals(p)){
			int pageSize=5;
			int currPageNo=1;
			int start = 0;
			String pageIndex=req.getParameter("pageIndex");
			String tid=req.getParameter("tid");
			System.out.println(tid);
			Page page=null;
			List<News> nlist=null;//条件查询的集合
			List<News> flist=null;//分页查询的集合
			NewsDao newsDao=new NewsDaoImpl();
			if(pageIndex!=null){
				currPageNo=Integer.parseInt(pageIndex);	
				start=(currPageNo-1)*pageSize;
			}
			if(tid==null||tid==""){
				String sql1="select * from news";
				String sql2="select * from news limit ?,?";
				nlist=newsDao.selectNews(sql1);
				flist=newsDao.selectNews(sql2,start,pageSize);				
			}else if(tid!=null){
				int ntid=Integer.parseInt(tid);
				String sql3="select * from news where ntid=?";
				String sql4="select * from news where ntid=? limit ?,?";
				nlist=newsDao.selectNews(sql3,ntid);
				flist=newsDao.selectNews(sql4,ntid,start,pageSize);
			}
			int totalCount=nlist.size();
			int totalPages=(totalCount/pageSize==0)?(totalCount/pageSize):(totalCount/pageSize+1);
			page=new Page(currPageNo,pageSize,totalCount,totalPages,flist);	
			String newsJson=JSON.toJSONStringWithDateFormat(page, "yyyy-MM-dd HH:mm:ss");	
			out.print(newsJson);
		    out.flush();
		    out.close();
		}else if("/topicServlet.to".equals(p)){
			TopicDao tdao=new TopicDaoImpl();
			List<Topic> tlist=tdao.getAllTopics();
			String topicJson=JSON.toJSONString(tlist);
			out.write(topicJson);
			out.flush();
		    out.close();
		}
			
	}
	
}
 
 

Page类:

package entity;

import java.io.Serializable;
import java.util.List;

public class Page implements Serializable {
	private int currPageNo; // 当前页码
	private int pageSize; // 页面大小,即每页显示记录数
	private int totalCount; // 记录总数
	private int totalPageCount; // 总页数
	private List<News> newsList; // 每页数据集合
	public int getCurrPageNo() {
		return currPageNo;
	}
	public void setCurrPageNo(int currPageNo) {
		this.currPageNo = currPageNo;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public int getTotalPageCount() {
		return totalPageCount;
	}
	public void setTotalPageCount(int totalPageCount) {
		this.totalPageCount = totalPageCount;
	}
	public List<News> getNewsList() {
		return newsList;
	}
	public void setNewsList(List<News> newsList) {
		this.newsList = newsList;
	}
	public Page(int currPageNo, int pageSize, int totalCount,
			int totalPageCount, List<News> newsList) {
		super();
		this.currPageNo = currPageNo;
		this.pageSize = pageSize;
		this.totalCount = totalCount;
		this.totalPageCount = totalPageCount;
		this.newsList = newsList;
	}
	
}

效果图:




猜你喜欢

转载自blog.csdn.net/lp_cq242/article/details/80530227