pjax分页

ajax的分页有一个小问题,就是点击浏览器的后退按钮不会起到作用,咱们点击下一页的时候浏览器的地址也不会改变,借助html5的history api可以解决这个问题,就是history.pushState,有人叫他们pjax,!!管他呢,直接上代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>烟花</title>
</head>

<body>
<button id="1">1</button>
<button id="2">2</button>
<button id="3">3</button>
<button id="4">4</button>
<button id="5">5</button>
<div id="box"></div>
</body>
 <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<script>
$('button').click(function () {

var state=new Object();
state.id=$(this).attr("id");
$.ajax({
type : 'GET', //这里可以换成 GET
url : '../pjax/pjax',
data : {
id: this.id,
},
success : function (response, stutas, xhr) {
$('#box').html(response);


history.pushState(state,state.id,"pjax.html?page="+state.id);
}
});
});
window.addEventListener("popstate",loadState,false);
function loadState(e){
	//console.log("id="+e.state.id);
	//alert(e.state.id);
	$.ajax({
			type : 'GET', //这里可以换成 GET
			url : '../pjax/pjax',
			data : {
			id: e.state.id,
			},
			success : function (response, stutas, xhr) {
				$('#box').html(response);
				var state=new Object();
				state.id=response;
				document.title=e.state.id;
				//history.pushState(state,state.id,"page="+state.id);
			}
});
	
}

</script>
</html>

servlet是这样的:

package pjax;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * Servlet implementation class pjax
 */
public class pjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public pjax() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String account = request.getParameter("id");
		PrintWriter out = response.getWriter();
		out.print(account);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

项目在myeclipse中是这样的:

运行之后显示如下截图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值